adventofcode/2020/Day09.cs

107 lines
2.5 KiB
C#
Raw Normal View History

2020-12-09 13:40:46 +00:00
using System;
using static System.Console;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Xunit;
namespace AdventOfCode {
public class Day09 {
2020-12-09 13:42:04 +00:00
static bool Valid(List<long> longs, int preambleSize, int target) {
2020-12-09 13:40:46 +00:00
for (int i = target - preambleSize; i < target - 1; i++) {
for (int j = i + 1; j < target; j++) {
if (i == j) {
continue;
}
2020-12-09 13:42:04 +00:00
if (longs[i] + longs[j] == longs[target]) {
2020-12-09 13:40:46 +00:00
return true;
}
}
}
return false;
}
2020-12-09 13:42:04 +00:00
static long FindInvalid(List<long> longs, int preambleSize) {
for (int target = preambleSize; target < longs.Count(); target++) {
if (!Valid(longs, preambleSize, target)) {
return longs[target];
2020-12-09 13:40:46 +00:00
}
}
throw new Exception("didn't find an invalid int");
}
2020-12-09 13:51:14 +00:00
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");
}
2020-12-09 13:40:46 +00:00
static long Part1() {
string[] input = File.ReadAllLines(Util.RootDir + "day09.txt");
2020-12-09 13:42:04 +00:00
List<long> longs = input.ToList().Select(long.Parse).ToList();
return FindInvalid(longs, 25);
2020-12-09 13:40:46 +00:00
}
2020-12-09 13:51:14 +00:00
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);
2020-12-09 13:40:46 +00:00
}
[Fact]
public static void Test() {
string[] example =
@"35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576".Split('\n');
2020-12-09 13:42:04 +00:00
List<long> longs = example.ToList().Select(long.Parse).ToList();
Assert.Equal(127, FindInvalid(longs, 5));
2020-12-09 13:40:46 +00:00
2020-12-09 13:51:14 +00:00
long invalidNumber = Part1();
Assert.Equal(50047984, invalidNumber);
Assert.Equal(5407707, Part2(invalidNumber));
2020-12-09 13:40:46 +00:00
}
}
}