day 9, part 2 solution
This commit is contained in:
parent
0cad16b5a4
commit
e7b9d4e44e
@ -33,14 +33,43 @@ namespace AdventOfCode {
|
|||||||
throw new Exception("didn't find an invalid int");
|
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() {
|
static long Part1() {
|
||||||
string[] input = File.ReadAllLines(Util.RootDir + "day09.txt");
|
string[] input = File.ReadAllLines(Util.RootDir + "day09.txt");
|
||||||
List<long> longs = input.ToList().Select(long.Parse).ToList();
|
List<long> longs = input.ToList().Select(long.Parse).ToList();
|
||||||
return FindInvalid(longs, 25);
|
return FindInvalid(longs, 25);
|
||||||
}
|
}
|
||||||
|
|
||||||
static int Part2() {
|
static long Part2(long target) {
|
||||||
return -1;
|
string[] input = File.ReadAllLines(Util.RootDir + "day09.txt");
|
||||||
|
List<long> longs = input.ToList().Select(long.Parse).ToList();
|
||||||
|
return FindWeakness(longs, target);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@ -69,8 +98,9 @@ namespace AdventOfCode {
|
|||||||
List<long> longs = example.ToList().Select(long.Parse).ToList();
|
List<long> longs = example.ToList().Select(long.Parse).ToList();
|
||||||
Assert.Equal(127, FindInvalid(longs, 5));
|
Assert.Equal(127, FindInvalid(longs, 5));
|
||||||
|
|
||||||
Assert.Equal(50047984, Part1());
|
long invalidNumber = Part1();
|
||||||
Assert.Equal(-1, Part2());
|
Assert.Equal(50047984, invalidNumber);
|
||||||
|
Assert.Equal(5407707, Part2(invalidNumber));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user