-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_04.rs
106 lines (86 loc) · 2.47 KB
/
day_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
use std::convert::identity;
use aoc_lib::{direction::ordinal::Direction, matrix::Grid};
use common::{solution, Answer};
use nd_vec::vector;
solution!("Ceres Search", 4);
fn part_a(input: &str) -> Answer {
let matrix = Grid::parse(input, identity);
let mut count = 0;
for y in 0..matrix.size.y() {
for x in 0..matrix.size.x() {
let start = vector!(x, y);
if *matrix.get(start).unwrap() != 'X' {
continue;
}
'outer: for dir in Direction::ALL {
let mut pos = start;
for expected in ['M', 'A', 'S'] {
let next = dir.try_advance(pos);
let Some(next) = next else { continue 'outer };
pos = next;
if Some(&expected) != matrix.get(pos) {
continue 'outer;
};
}
count += 1;
}
}
}
count.into()
}
/// The directions to advance from the middle 'A' for each MAS instance.
const MAS_DIRECTIONS: [[Direction; 2]; 2] = [
[Direction::NorthEast, Direction::SouthWest],
[Direction::SouthEast, Direction::NorthWest],
];
fn part_b(input: &str) -> Answer {
let matrix = Grid::parse(input, identity);
let mut count = 0;
for y in 0..matrix.size.y() {
'outer: for x in 0..matrix.size.x() {
let start = vector!(x, y);
if *matrix.get(start).unwrap() != 'A' {
continue;
}
for mas in MAS_DIRECTIONS {
let (mut m, mut s) = (false, false);
for dir in mas {
let Some(&chr) = dir.try_advance(start).and_then(|x| matrix.get(x)) else {
continue 'outer;
};
m |= chr == 'M';
s |= chr == 'S';
}
if !(m && s) {
continue 'outer;
}
}
count += 1;
}
}
count.into()
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 18.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 9.into());
}
}