Browse Source

day 9, part 2 solution

main
Colin McMillen 11 months ago
parent
commit
e7b9d4e44e
  1. 38
      2020/Day09.cs

38
2020/Day09.cs

@ -33,14 +33,43 @@ namespace AdventOfCode {
throw new Exception("didn't find an invalid int");
}
static long CalculateWeakness(List<long> longs, int minIndex, int maxIndex) {
long largest = 0;
long smallest = long.MaxValue;
for (int i = minIndex; i <= maxIndex; i++) {
if (longs[i] > largest) {
largest = longs[i];
}
if (longs[i] < smallest) {
smallest = longs[i];
}
}
return smallest + largest;
}
static long FindWeakness(List<long> longs, long target) {
for (int i = 0; i < longs.Count() - 1; i++) {
long total = 0;
for (int j = i; j < longs.Count() && total < target; j++) {
total += longs[j];
if (total == target) {
return CalculateWeakness(longs, i, j);
}
}
}
throw new Exception("didn't find a weakness");
}
static long Part1() {
string[] input = File.ReadAllLines(Util.RootDir + "day09.txt");
List<long> longs = input.ToList().Select(long.Parse).ToList();
return FindInvalid(longs, 25);
}
static int Part2() {
return -1;
static long Part2(long target) {
string[] input = File.ReadAllLines(Util.RootDir + "day09.txt");
List<long> longs = input.ToList().Select(long.Parse).ToList();
return FindWeakness(longs, target);
}
[Fact]
@ -69,8 +98,9 @@ namespace AdventOfCode {
List<long> longs = example.ToList().Select(long.Parse).ToList();
Assert.Equal(127, FindInvalid(longs, 5));
Assert.Equal(50047984, Part1());
Assert.Equal(-1, Part2());
long invalidNumber = Part1();
Assert.Equal(50047984, invalidNumber);
Assert.Equal(5407707, Part2(invalidNumber));
}
}
}
Loading…
Cancel
Save