64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.Immutable;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading;
|
|
|
|
namespace AoC {
|
|
|
|
internal class Day9 {
|
|
|
|
private const int preamble = 25;
|
|
|
|
internal void Solve() {
|
|
var numbers = File.ReadAllText("day9/input")
|
|
.Split("\n", StringSplitOptions.RemoveEmptyEntries)
|
|
.Select(long.Parse)
|
|
.ToList();
|
|
|
|
bool ExistTwo(ISet<long> current, long target) =>
|
|
current.Any(c => current.Contains(target - c));
|
|
|
|
Queue<long> currentQueue = new Queue<long>();
|
|
ISet<long> currentSet = new HashSet<long>();
|
|
numbers.Take(preamble).ToList().ForEach(i => {
|
|
currentQueue.Enqueue(i);
|
|
currentSet.Add(i);
|
|
});
|
|
|
|
foreach (var n in numbers.Skip(preamble)) {
|
|
if (!ExistTwo(currentSet, n)) {
|
|
Console.WriteLine(n);
|
|
break;
|
|
}
|
|
|
|
long firstInserted = currentQueue.Dequeue();
|
|
currentQueue.Enqueue(n);
|
|
currentSet.Remove(firstInserted);
|
|
currentSet.Add(n);
|
|
}
|
|
|
|
// part two
|
|
const long contiguousNumber = 69316178;
|
|
|
|
long sum = 0;
|
|
Queue<long> contiguousQueue = new Queue<long>();
|
|
foreach (var n in numbers) {
|
|
if (sum < contiguousNumber) {
|
|
contiguousQueue.Enqueue(n);
|
|
sum += n;
|
|
}
|
|
while (sum > contiguousNumber) {
|
|
sum -= contiguousQueue.Dequeue();
|
|
}
|
|
if (sum == contiguousNumber) {
|
|
long res = contiguousQueue.Min() + contiguousQueue.Max();
|
|
Console.WriteLine(res);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |