generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
13.rs
112 lines (101 loc) · 3.88 KB
/
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
advent_of_code::solution!(13);
pub fn part_one(input: &str) -> Option<u32> {
Some(
input
.split("\n\n")
.map(|pattern| {
let pattern = pattern.as_bytes();
let cols = pattern
.iter()
.position(|&ch| ch == b'\n')
.expect("should be more than one row");
let rows = (pattern.len() + 1) / (cols + 1);
// Try column mirroring.
let col_mirror = (1..cols).find(|&col_split| {
(0..col_split.min(cols - col_split)).all(|offset| {
(0..rows).all(|r| {
pattern[r * (cols + 1) + col_split - offset - 1]
== pattern[r * (cols + 1) + col_split + offset]
})
})
});
if let Some(col_mirror) = col_mirror {
return col_mirror as u32;
}
// Try row mirroring.
let row_mirror = (1..rows).find(|&row_split| {
(0..row_split.min(rows - row_split)).all(|offset| {
(0..cols).all(|c| {
pattern[(row_split - offset - 1) * (cols + 1) + c]
== pattern[(row_split + offset) * (cols + 1) + c]
})
})
});
if let Some(row_mirror) = row_mirror {
return row_mirror as u32 * 100;
}
unreachable!("every pattern shold have a solution")
})
.sum(),
)
}
pub fn part_two(input: &str) -> Option<u32> {
Some(
input
.split("\n\n")
.map(|pattern| {
let pattern = pattern.as_bytes();
let cols = pattern
.iter()
.position(|&ch| ch == b'\n')
.expect("should be more than one row");
let rows = (pattern.len() + 1) / (cols + 1);
let col_mirror = (1..cols).find(|&col_split| {
(0..col_split.min(cols - col_split))
.flat_map(|offset| {
(0..rows).filter(move |&r| {
pattern[r * (cols + 1) + col_split - offset - 1]
!= pattern[r * (cols + 1) + col_split + offset]
})
})
.take(2)
.count()
== 1
});
if let Some(col_mirror) = col_mirror {
return col_mirror as u32;
}
let row_mirror = (1..rows).find(|&row_split| {
(0..row_split.min(rows - row_split))
.flat_map(|offset| {
(0..cols).filter(move |c| {
pattern[(row_split - offset - 1) * (cols + 1) + c]
!= pattern[(row_split + offset) * (cols + 1) + c]
})
})
.take(2)
.count()
== 1
});
if let Some(row_mirror) = row_mirror {
return row_mirror as u32 * 100;
}
unreachable!("every pattern shold have a solution")
})
.sum(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(405));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(400));
}
}