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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
use {
anyhow::{
anyhow,
Context,
Result,
},
std::{
env::args,
fmt,
fmt::Display,
fs::File,
io::{
BufRead,
BufReader,
},
path::Path,
},
};
#[derive(Clone)]
struct BingoBoard {
size: usize,
values: Vec<u8>,
called: Vec<bool>,
completed: Option<u8>,
}
impl BingoBoard {
fn new<'a, I: IntoIterator<Item = &'a u8> + Copy>(grid: I) -> Self {
let size = 5;
let values = (&grid).into_iter().copied().collect();
let called = vec![false; grid.into_iter().count()];
let completed = None;
Self {
size,
values,
called,
completed,
}
}
fn play(&mut self, num: &u8) -> Result<bool> {
if self.completed.is_some() {
return Ok(false);
}
for y in 0..self.size {
for x in 0..self.size {
let value = self.values.get(y * self.size + x)
.ok_or(anyhow!("Invalid BingoBoard"))?;
if value == num {
self.called[y * self.size + x] = true;
}
}
}
for y in 0..self.size {
let mut count = 0;
for x in 0..self.size {
if *self.called.get(y * self.size + x).ok_or(anyhow!("Invalid BingoBoard"))? {
count += 1;
}
if count == self.size {
self.completed = Some(*num);
return Ok(true);
}
}
}
for x in 0..self.size {
let mut count = 0;
for y in 0..self.size {
if *self.called.get(y * self.size + x).ok_or(anyhow!("Invalid BingoBoard"))? {
count += 1;
}
if count == self.size {
self.completed = Some(*num);
return Ok(true);
}
}
}
Ok(false)
}
fn sum_unmarked(&self) -> Result<usize> {
let mut sum = 0;
for y in 0..self.size {
for x in 0..self.size {
let value = self.values.get(y * self.size + x)
.ok_or(anyhow!("Invalid BingoBoard"))?;
if ! *self.called.get(y * self.size + x).ok_or(anyhow!("Invalid BingoBoard"))? {
sum += *value as usize;
}
}
}
Ok(sum)
}
}
impl Display for BingoBoard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = String::new();
for y in 0..self.size {
for x in 0..self.size {
let value = self.values.get(y * self.size + x).ok_or(std::fmt::Error)?;
if *self.called.get(y * self.size + x).ok_or(std::fmt::Error)? {
s += &format!("[{:2}] ", value);
} else {
s += &format!(" {:2} ", value);
}
}
s += "\n";
}
if let Some(won) = self.completed {
s += &format!("Winning number: {}\n", won);
}
write!(f, "{}", s)
}
}
#[derive(Clone)]
struct BingoGame {
numbers: Vec<u8>,
boards: Vec<BingoBoard>,
}
impl BingoGame {
fn new() -> Self {
Self {
numbers: vec![],
boards: vec![],
}
}
}
fn read_input<T: AsRef<Path>>(filename: T) -> Result<BingoGame> {
let reader = BufReader::new(File::open(filename)?);
let mut game = BingoGame::new();
let mut boards: Vec<BingoBoard> = vec![];
let mut lines = reader.lines();
let draw_line = lines.next().ok_or(anyhow!("Could not parse draw_line"))?
.map_err(|err| anyhow!("{}", err))?;
let mut buffer: Vec<u8> = vec![];
for line in lines {
let l = line?;
if l.is_empty() {
if ! buffer.is_empty() {
let board = BingoBoard::new(&buffer);
boards.push(board);
}
buffer = vec![];
} else {
buffer.append(&mut l.split_whitespace().map(|v| v.parse()
.map_err(|_| anyhow!("Parse error"))).collect::<Result<_>>()?);
}
}
let board = BingoBoard::new(&buffer);
boards.push(board);
game.numbers = draw_line.split(',').map(|v| v.parse().map_err(|err| anyhow!("{}", err)))
.collect::<Result<_>>()?;
game.boards = boards;
Ok(game)
}
fn part1(game: &BingoGame) -> Result<usize> {
let mut game_mut = game.clone();
for num in &game_mut.numbers {
for board in &mut game_mut.boards {
if board.play(num)? {
// println!("{}", board);
return Ok(board.sum_unmarked()? * *num as usize);
}
}
}
Err(anyhow!("No winner"))
}
fn part2(game: &BingoGame) -> Result<usize> {
let mut game_mut = game.clone();
let mut last_winner = None;
for num in &game_mut.numbers {
for (index, board) in &mut game_mut.boards.iter_mut().enumerate() {
if board.play(num)? {
last_winner = Some(index);
}
}
}
if let Some(winner) = last_winner {
let board = &game_mut.boards[winner];
let unmarked_sum = board.sum_unmarked()?;
let won = board.completed.ok_or(anyhow!("No winning number"))? as usize;
// println!("Winning board: {} ({} * {})", winner + 1, unmarked_sum, won);
// println!("{}", board);
Ok(unmarked_sum * won)
} else {
Err(anyhow!("No winner"))
}
}
fn main() -> Result<()> {
let ( do_part_1, do_part_2 ) = aoc::do_parts();
let filename = args().nth(1).ok_or(anyhow!("Missing input filename"))?;
let input = read_input(filename).context("Could not read input")?;
if do_part_1 {
let solution = part1(&input).context("No solution for part 1")?;
println!("Part1, solution found to be: {}", solution);
}
if do_part_2 {
let solution = part2(&input).context("No solution for part 2")?;
println!("Part2, solution found to be: {}", solution);
}
Ok(())
}
|