From 000002301f132c1776d167ecb25a592727a01716 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Jane=C5=BEi=C4=8D?= Date: Mon, 11 Dec 2023 17:51:58 +0100 Subject: [PATCH] solution: day 11 --- data/examples/11.txt | 10 ++++++ src/bin/11.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 data/examples/11.txt create mode 100644 src/bin/11.rs diff --git a/data/examples/11.txt b/data/examples/11.txt new file mode 100644 index 000000000..986aad4 --- /dev/null +++ b/data/examples/11.txt @@ -0,0 +1,10 @@ +...#...... +.......#.. +#......... +.......... +......#... +.#........ +.........# +.......... +.......#.. +#...#..... diff --git a/src/bin/11.rs b/src/bin/11.rs new file mode 100644 index 000000000..7ee9f99 --- /dev/null +++ b/src/bin/11.rs @@ -0,0 +1,78 @@ +use std::collections::HashSet; + +fn parse_input(input: &str) -> (Vec<(usize, usize)>, HashSet, HashSet) { + let mut galaxies = Vec::new(); + let mut rows = HashSet::new(); + let mut columns = HashSet::from_iter(1..(input.lines().next().unwrap().len())); + + for (y, line) in input.lines().enumerate() { + let mut found = false; + for (x, c) in line.chars().enumerate() { + if c == '#' { + galaxies.push((y, x)); + found = true; + } + columns.remove(&x); + } + if !found { + rows.insert(y); + } + } + + (galaxies, rows, columns) +} + +fn solve(input: &str, explode: usize) -> Option { + let (galaxies, rows, columns) = parse_input(input); + + let mut counter = 0; + + for ((y1, x1), (y2, x2)) in galaxies + .iter() + .copied() + .enumerate() + .flat_map(|(i, x)| galaxies.iter().skip(i + 1).copied().map(move |y| (x, y))) + { + let y_abs = y1.abs_diff(y2); + let x_abs = x1.abs_diff(x2); + let x_extra = columns + .iter() + .filter(|x| (x1..=x2).contains(x) || (x2..=x1).contains(x)) + .count(); + let y_extra = rows + .iter() + .filter(|y| (y1..=y2).contains(y) || (y2..=y1).contains(y)) + .count(); + counter += x_abs + y_abs + (x_extra + y_extra) * (explode - 1); + } + + Some(counter) +} + +pub fn part_one(input: &str) -> Option { + solve(input, 2) +} + +pub fn part_two(input: &str) -> Option { + solve(input, 1_000_000) +} + +aoc::solution!(11); + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_part_one() { + assert_eq!( + part_one(&aoc::template::read_file("examples", 11)), + Some(374) + ); + } + #[test] + fn test_part_two() { + let input = aoc::template::read_file("examples", 11); + assert_eq!(solve(&input, 10), Some(1030)); + assert_eq!(solve(&input, 100), Some(8410)); + } +}