Skip to content

Commit

Permalink
day(2): Red-Nosed Reports :reindeer:
Browse files Browse the repository at this point in the history
  • Loading branch information
adamrodger committed Dec 2, 2024
1 parent f07a7c3 commit 9a73940
Show file tree
Hide file tree
Showing 3 changed files with 1,099 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/AdventOfCode/Day2.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AdventOfCode.Utilities;

namespace AdventOfCode
{
/// <summary>
/// Solver for Day 2
/// </summary>
public class Day2
{
public int Part1(string[] input)
{
return input.Select(l => l.Numbers<int>()).Count(IsSafe);
}

public int Part2(string[] input)
{
return input.Select(l => l.Numbers<int>()).Count(ReallySafe);
}

private static bool IsSafe(ICollection<int> numbers)
{
var pairs = numbers.Zip(numbers.Skip(1));
var diffs = pairs.Select(pair => pair.First - pair.Second).ToArray();

var signs = Math.Abs(diffs.Sum(Math.Sign));

if (signs != diffs.Length) return false;

if (diffs.Select(Math.Abs).Any(d => d is 0 or > 3)) return false;

return true;
}

private static bool ReallySafe(ICollection<int> numbers)
{
if (IsSafe(numbers)) return true;

for (int i = 0; i < numbers.Count; i++)
{
var clone = numbers.ToList();
clone.RemoveAt(i);

if (IsSafe(clone)) return true;
}

return false;
}
}
}
Loading

0 comments on commit 9a73940

Please sign in to comment.