-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4.rs
100 lines (84 loc) · 2.22 KB
/
day4.rs
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
//! [Day 4: Giant Squid](https://adventofcode.com/2021/day/4)
/// main function
fn main() {
let data = aoc::load_input_data_vec(4);
let drawn = data[0]
.split(',')
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
// load the grids
let mut grids = vec![];
let mut i = 2;
while i < data.len() {
let mut grid = [[0_i32; 5]; 5];
for y in 0..5 {
let line = data[i + y]
.split_whitespace()
.filter_map(|s| s.parse::<i32>().ok())
.collect::<Vec<i32>>();
grid[y][..5].clone_from_slice(&line[..5]);
}
grids.push(grid);
i += 6;
}
let mut first_win = false;
let mut last_draw = 0;
for draw in drawn {
for grid in &mut grids {
if grid[0][0] == -2 {
// grid invalidated
continue;
}
for line in grid.iter_mut() {
for val in line {
if *val == draw {
*val = -1; // clear the case
}
}
}
if win(grid) {
last_draw = draw * sum(grid);
if !first_win {
first_win = true;
println!("{last_draw}");
}
grid[0][0] = -2; // invalidate the grid
}
}
}
println!("{last_draw}");
}
/// sum computes the sum of non-cleared cases
fn sum(grid: &[[i32; 5]; 5]) -> i32 {
let mut s = 0;
for line in grid {
for val in line {
if *val != -1 {
s += *val;
}
}
}
s
}
/// `has_win` returns true if the grid has an cleared row or column
fn win(grid: &[[i32; 5]; 5]) -> bool {
for i in 0..5 {
if grid[i][0] == -1
&& grid[i][1] == -1
&& grid[i][2] == -1
&& grid[i][3] == -1
&& grid[i][4] == -1
{
return true;
}
if grid[0][i] == -1
&& grid[1][i] == -1
&& grid[2][i] == -1
&& grid[3][i] == -1
&& grid[4][i] == -1
{
return true;
}
}
false
}