-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04.rs
110 lines (99 loc) · 2.47 KB
/
04.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
101
102
103
104
105
106
107
108
109
110
#![feature(test)]
use rustc_hash::FxHashSet;
struct Input {
nums: Vec<i32>,
boards: Vec<Vec<Vec<i32>>>,
}
fn setup(input: &str) -> Input {
let nums = input
.lines()
.next()
.unwrap()
.split(',')
.map(|n| n.parse().unwrap())
.collect();
let boards = input
.split("\n\n")
.skip(1)
.map(|board| {
board
.lines()
.map(|line| {
line.split_whitespace()
.map(|n| n.parse().unwrap())
.collect()
})
.collect()
})
.collect();
Input { nums, boards }
}
struct State {
boards: Vec<Vec<Vec<i32>>>,
marked: FxHashSet<i32>,
}
impl State {
fn from_input(input: &Input) -> State {
State {
boards: input.boards.clone(),
marked: FxHashSet::default(),
}
}
fn mark(&mut self, num: i32) {
self.marked.insert(num);
}
fn check_board(&self, board: usize) -> bool {
let board = &self.boards[board];
for row in board {
if row.iter().all(|n| self.marked.contains(n)) {
return true;
}
}
for i in 0..board[0].len() {
if board.iter().all(|row| self.marked.contains(&row[i])) {
return true;
}
}
false
}
fn get_score(&self, board: usize) -> i32 {
self.boards[board]
.iter()
.flatten()
.filter(|n| !self.marked.contains(n))
.copied()
.reduce(|a, b| a + b)
.unwrap()
}
}
fn part1(input: &Input) -> String {
let mut state = State::from_input(input);
for num in &input.nums {
state.mark(*num);
for i in 0..state.boards.len() {
if state.check_board(i) {
return (num * state.get_score(i)).to_string();
}
}
}
panic!();
}
fn part2(input: &Input) -> String {
let mut state = State::from_input(input);
for num in &input.nums {
state.mark(*num);
let mut i = 0;
while i < state.boards.len() {
if !state.check_board(i) {
i += 1;
continue;
}
if state.boards.len() == 1 {
return (num * state.get_score(i)).to_string();
}
state.boards.remove(i);
}
}
panic!()
}
aoc::main!(2021, 4, ex: 1);