summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_13.rs
diff options
context:
space:
mode:
authorJustin Wernick <justin@worthe-it.co.za>2023-12-14 13:53:12 +0200
committerJustin Wernick <justin@worthe-it.co.za>2023-12-14 13:53:12 +0200
commite37434b49728141f92a3002fdb0a2f07108db28f (patch)
tree715c65ade45fa4c9317dd6e57990c2d92554b9f5 /2023/src/bin/day_13.rs
parentd985f2802d65691ee18b23c261cb2b12b7e6146f (diff)
Day 13 part 1
Diffstat (limited to '2023/src/bin/day_13.rs')
-rw-r--r--2023/src/bin/day_13.rs74
1 files changed, 66 insertions, 8 deletions
diff --git a/2023/src/bin/day_13.rs b/2023/src/bin/day_13.rs
index b3a610b..b2ef8aa 100644
--- a/2023/src/bin/day_13.rs
+++ b/2023/src/bin/day_13.rs
@@ -1,19 +1,77 @@
-use nom::IResult;
+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_2.txt")?;
- let parsed = Example::parser(&input).unwrap().1;
- dbg!(&parsed);
+ 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 Example;
+struct ManyMaps(Vec<Map>);
-impl Example {
- fn parser(_input: &str) -> IResult<&str, Self> {
- todo!()
+#[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
}