day 9, part 2 solution

This commit is contained in:
Colin McMillen 2020-12-09 08:51:14 -05:00
parent 0cad16b5a4
commit e7b9d4e44e

View File

@ -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));
}
}
}