-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_13.rs
119 lines (98 loc) Β· 2.63 KB
/
day_13.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
use common::{solution, Answer};
solution!("Point of Incidence", 13);
fn part_a(input: &str) -> Answer {
let valleys = parse(input);
solve(&valleys, 0).into()
}
fn part_b(input: &str) -> Answer {
let valleys = parse(input);
solve(&valleys, 1).into()
}
fn solve(valleys: &[Valley], limit: usize) -> usize {
valleys
.iter()
.filter_map(|valley| {
valley
.horizontal_reflection(limit)
.map(|x| 100 * x)
.or_else(|| valley.vertical_reflection(limit))
})
.sum()
}
struct Valley {
tiles: Vec<Vec<char>>,
}
fn parse(input: &str) -> Vec<Valley> {
let mut out = Vec::new();
for set in input.split("\n\n") {
let tiles = set.lines().map(|line| line.chars().collect()).collect();
out.push(Valley { tiles });
}
out
}
impl Valley {
// Find a horizontal reflection in the valley.
// Horizontal reflections is from left to right.
fn horizontal_reflection(&self, error: usize) -> Option<usize> {
for mid in 1..=self.tiles.len() - 1 {
let side_len = mid.min(self.tiles.len() - mid);
let start = mid - side_len;
let mut diff = 0;
for a in start..mid {
let b = mid * 2 - a - 1;
diff += (0..self.tiles[a].len())
.filter(|&i| self.tiles[a][i] != self.tiles[b][i])
.count();
}
if diff == error {
return Some(mid);
}
}
None
}
fn vertical_reflection(&self, error: usize) -> Option<usize> {
for mid in 1..=self.tiles[0].len() - 1 {
let side_len = mid.min(self.tiles[0].len() - mid);
let start = mid - side_len;
let mut diff = 0;
for a in start..mid {
let b = mid * 2 - a - 1;
diff += (0..self.tiles.len())
.filter(|&i| self.tiles[i][a] != self.tiles[i][b])
.count();
}
if diff == error {
return Some(mid);
}
}
None
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
#.##..##.
..#.##.#.
##......#
##......#
..#.##.#.
..##..##.
#.#.##.#.
#...##..#
#....#..#
..##..###
#####.##.
#####.##.
..##..###
#....#..#
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 405.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 400.into());
}
}