-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
73 lines (57 loc) · 1.81 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using AdventOfCode._2021_04;
using AdventOfCode.Common;
using var inputReader = Resources.GetResourceStream();
var drawnNumbers = inputReader.ReadLine()!.SplitToNumbers();
inputReader.ReadLine();
var boards = new List<Board>();
while (!inputReader.EndOfStream)
{
boards.Add(Board.FromStream(inputReader));
inputReader.ReadLine();
}
static int GetFirstWinningBoardScore(IEnumerable<int> drawnNumbers, IEnumerable<Board> boards)
{
foreach (var number in drawnNumbers)
{
var winningBoard = boards.FirstOrDefault(board => board.CrossNumber(number));
if (winningBoard != null)
{
return number * winningBoard.GetSumOfRemainingNumbers();
}
}
throw new Exception("No winning board");
}
static int GetLastWinningBoardScore(IEnumerable<int> drawnNumbers, IEnumerable<Board> boards)
{
var currentRound = new Queue<Board>(boards);
var nextRound = new Queue<Board>();
Board? lastWinningBoard = null;
foreach (var number in drawnNumbers)
{
while (currentRound.Count != 0)
{
var board = currentRound.Dequeue();
if (!board.CrossNumber(number))
{
nextRound.Enqueue(board);
}
else
{
lastWinningBoard = board;
}
}
if (nextRound.Count == 0)
{
return number * (lastWinningBoard ?? throw new Exception("No winning board")).GetSumOfRemainingNumbers();
}
currentRound = nextRound;
nextRound = new();
}
throw new Exception("Multiple winning boards");
}
Console.WriteLine($"Part 1: {GetFirstWinningBoardScore(drawnNumbers, boards)}");
foreach (var board in boards)
{
board.Reset();
}
Console.WriteLine($"Part 2: {GetLastWinningBoardScore(drawnNumbers, boards)}");