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
|
use nom::{
character::complete::{line_ending, one_of},
combinator::map,
multi::{many1, separated_list1},
sequence::pair,
IResult,
};
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let input = fs::read_to_string("inputs/day_13.txt")?;
let parsed = ManyMaps::parser(&input).unwrap().1;
dbg!(&parsed.reflection_score_sum());
Ok(())
}
#[derive(Debug)]
struct ManyMaps(Vec<Map>);
#[derive(Debug)]
struct Map {
rows: Vec<String>,
cols: Vec<String>,
}
impl ManyMaps {
fn parser(input: &str) -> IResult<&str, Self> {
map(
separated_list1(pair(line_ending, line_ending), Map::parser),
ManyMaps,
)(input)
}
fn reflection_score_sum(&self) -> usize {
self.0.iter().map(|m| m.reflection_score()).sum()
}
}
impl Map {
fn parser(input: &str) -> IResult<&str, Self> {
map(separated_list1(line_ending, many1(one_of(".#"))), |rows| {
Map {
rows: rows
.iter()
.map(|char_array| char_array.iter().collect::<String>())
.collect(),
cols: (0..rows[0].len())
.map(|i| rows.iter().map(|row| row[i]).collect::<String>())
.collect(),
}
})(input)
}
fn reflection_score(&self) -> usize {
reflection_i(&self.cols)
.or_else(|| reflection_i(&self.rows).map(|y| y * 100))
.expect("No reflection!")
}
}
fn reflection_i(rows: &[String]) -> Option<usize> {
for i in 1..rows.len() {
let mut is_reflection = true;
let mut d = 1;
while is_reflection && d <= i && d + i - 1 < rows.len() {
if rows[i - d] != rows[i + d - 1] {
is_reflection = false;
}
d += 1;
}
if is_reflection {
return Some(i);
}
}
None
}
|