-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay02.cs
85 lines (72 loc) · 2.22 KB
/
Day02.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
namespace advent_of_code_csharp_2024;
public static class Day02
{
public static readonly string InputFilename = @"../../../Day02_input.txt";
public static List<int> ParseLine(string line)
{
return line.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
}
public enum IsSafeEnum
{
Increasing,
Decreasing,
Unsafe
}
public static bool IsSafe(List<int> line)
{
var lookup =
line
.Zip(line.Skip(1).ToList(),
(a, b) =>
{
var diff = a - b;
if (diff == 0) return IsSafeEnum.Unsafe;
if (diff < -3) return IsSafeEnum.Unsafe;
if (diff > 3) return IsSafeEnum.Unsafe;
if (diff < 0) return IsSafeEnum.Decreasing;
if (diff > -3) return IsSafeEnum.Increasing;
throw new Exception($"Unexpected difference {diff}");
})
.ToLookup(x => x);
if (lookup.Count == 0)
{
return true;
}
return IsIncreasingOrDecreasingOnly(lookup);
}
public static bool IsSaveTolerant(List<int> line)
{
if (IsSafe(line))
{
return true;
}
for (int i = 0; i < line.Count; i++)
{
var removeLevel = new List<int>(line);
removeLevel.RemoveAt(i);
if (IsSafe(removeLevel))
{
return true;
}
}
return false;
}
public static bool IsIncreasingOrDecreasingOnly(ILookup<IsSafeEnum, IsSafeEnum> lookup)
{
if (lookup.Contains(IsSafeEnum.Unsafe))
{
return false;
}
if (lookup.Contains(IsSafeEnum.Decreasing) && !lookup.Contains(IsSafeEnum.Increasing))
{
return true;
}
if (!lookup.Contains(IsSafeEnum.Decreasing) && lookup.Contains(IsSafeEnum.Increasing))
{
return true;
}
return false;
}
}