-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
day(2): Red-Nosed Reports :reindeer:
- Loading branch information
1 parent
f07a7c3
commit 9a73940
Showing
3 changed files
with
1,099 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
Oops, something went wrong.