-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfour.rs
127 lines (119 loc) · 4.01 KB
/
four.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use libaoc::{Day, DayNumber};
const BOARDWIDTH: usize = 5;
const BOARDHEIGHT: usize = 5;
const BOARDSIZE: usize = BOARDHEIGHT * BOARDWIDTH;
fn check_board(boards: &[(usize, bool)], board_number: usize) -> Option<usize> {
let board = &boards[board_number * BOARDSIZE..board_number * BOARDSIZE + BOARDSIZE];
// lines
for i in 0..BOARDHEIGHT {
let check = board[i * BOARDWIDTH..i * BOARDWIDTH + BOARDWIDTH]
.iter()
.filter(|(_, b)| *b)
.count();
if check == 5 {
return Some(
board
.iter()
.filter(|(_, b)| !*b)
.fold(0, |sum, (a, _)| sum + *a),
);
}
}
// cols
'c: for i in 0..BOARDWIDTH {
for j in 0..BOARDHEIGHT {
if !board[j * BOARDWIDTH + i].1 {
continue 'c;
}
}
return Some(
board
.iter()
.filter(|(_, b)| !*b)
.fold(0, |sum, (a, _)| sum + *a),
);
}
None
}
pub fn four() -> Day<2021> {
Day::new(
DayNumber::Four,
|input| {
let numbers = input
.split_once('\n')
.unwrap()
.0
.split(',')
.map(|a| a.parse::<usize>().unwrap())
.collect::<Vec<usize>>();
let mut boards = input
.lines()
.skip(1)
.filter(|&line| !line.is_empty())
.map(|line| {
line.split_whitespace()
.map(|number| (number.parse::<usize>().unwrap(), false))
.collect::<Vec<(usize, bool)>>()
})
.flatten()
.collect::<Vec<(usize, bool)>>();
for &number in numbers.iter() {
boards.iter_mut().for_each(|(n, marked)| {
if *n == number {
*marked = true
}
});
for board in 0..(boards.len() / BOARDSIZE) {
if let Some(result) = check_board(&boards, board) {
return Box::new(result * number);
}
}
}
unreachable!();
},
|input| {
let numbers = input
.split_once('\n')
.unwrap()
.0
.split(',')
.map(|a| a.parse::<usize>().unwrap())
.collect::<Vec<usize>>();
let mut boards = input
.lines()
.skip(1)
.filter(|&line| !line.is_empty())
.map(|line| {
line.split_whitespace()
.map(|number| (number.parse::<usize>().unwrap(), false))
.collect::<Vec<(usize, bool)>>()
})
.flatten()
.collect::<Vec<(usize, bool)>>();
let mut all_boards = (0..(boards.len() / BOARDSIZE)).collect::<Vec<usize>>();
for &number in numbers.iter() {
boards.iter_mut().for_each(|(n, marked)| {
if *n == number {
*marked = true
}
});
for board in 0..(boards.len() / BOARDSIZE) {
if !all_boards.contains(&board) {
continue;
}
if let Some(result) = check_board(&boards, board) {
if all_boards.len() == 1 && all_boards[0] == board {
return Box::new(result * number);
}
all_boards = all_boards
.iter()
.filter(|&b| *b != board)
.copied()
.collect::<Vec<usize>>();
}
}
}
unreachable!();
},
)
}