From 59cfa274c0f05982c989c408b4ab402735a5910d Mon Sep 17 00:00:00 2001 From: Burnus Date: Sun, 8 Dec 2024 10:28:36 +0100 Subject: [PATCH] Add 2024 Day 08 --- 2024/day08_resonant_collinearity/Cargo.toml | 13 ++ 2024/day08_resonant_collinearity/challenge.md | 150 +++++++++++++++++ 2024/day08_resonant_collinearity/src/lib.rs | 157 ++++++++++++++++++ .../tests/challenge_input | 50 ++++++ .../tests/sample_input | 12 ++ 5 files changed, 382 insertions(+) create mode 100644 2024/day08_resonant_collinearity/Cargo.toml create mode 100644 2024/day08_resonant_collinearity/challenge.md create mode 100644 2024/day08_resonant_collinearity/src/lib.rs create mode 100644 2024/day08_resonant_collinearity/tests/challenge_input create mode 100644 2024/day08_resonant_collinearity/tests/sample_input diff --git a/2024/day08_resonant_collinearity/Cargo.toml b/2024/day08_resonant_collinearity/Cargo.toml new file mode 100644 index 0000000..c788c03 --- /dev/null +++ b/2024/day08_resonant_collinearity/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "day08_resonant_collinearity" +version = "0.1.0" +edition = "2021" + +[dependencies] + +[dev-dependencies] +# criterion = "0.5.1" + +[[bench]] +name = "test_benchmark" +harness = false diff --git a/2024/day08_resonant_collinearity/challenge.md b/2024/day08_resonant_collinearity/challenge.md new file mode 100644 index 0000000..1b239b5 --- /dev/null +++ b/2024/day08_resonant_collinearity/challenge.md @@ -0,0 +1,150 @@ +You find yourselves on the [roof](/2016/day/25) of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar *huge antenna*. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific *frequency* indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +``` +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ + +``` + +The signal only applies its nefarious effect at specific *antinodes* based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency `a`, they create the two antinodes marked with `#`: + +``` +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... + +``` + +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +``` +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... + +``` + +Antennas with different frequencies don't create antinodes; `A` and `a` count as different frequencies. However, antinodes *can* occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital `A` creates no antinodes but has a lowercase-`a`-frequency antinode at its location: + +``` +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... + +``` + +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost `A`-frequency antenna: + +``` +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. + +``` + +Because the topmost `A`-frequency antenna overlaps with a `0`-frequency antinode, there are `*14*` total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. *How many unique locations within the bounds of the map contain an antinode?* + +Your puzzle answer was `354`. + +\--- Part Two --- +---------- + +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. + +Whoops! + +After updating your model, it turns out that an antinode occurs at *any grid position* exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). + +So, these three `T`-frequency antennas now create many antinodes: + +``` +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... + +``` + +In fact, the three `T`-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to `*9*`. + +The original example now has `*34*` antinodes, including the antinodes that appear on every antenna: + +``` +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## + +``` + +Calculate the impact of the signal using this updated model. *How many unique locations within the bounds of the map contain an antinode?* + +Your puzzle answer was `1263`. + +Both parts of this puzzle are complete! They provide two gold stars: \*\* + +At this point, you should [return to your Advent calendar](/2024) and try another puzzle. + +If you still want to see it, you can [get your puzzle input](8/input). \ No newline at end of file diff --git a/2024/day08_resonant_collinearity/src/lib.rs b/2024/day08_resonant_collinearity/src/lib.rs new file mode 100644 index 0000000..4bea5c0 --- /dev/null +++ b/2024/day08_resonant_collinearity/src/lib.rs @@ -0,0 +1,157 @@ +use core::fmt::Display; +use std::collections::{HashMap, HashSet}; + +#[derive(Debug, PartialEq, Eq)] +pub enum ParseError { + EmptyMap, + NonRectangular, + ParseCharError(char), +} + +impl Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::EmptyMap => write!(f, "Input can't be empty"), + Self::NonRectangular => write!(f, "Input lines must be of equal length"), + Self::ParseCharError(e) => write!(f, "Unable to parse {e} into an antenna. Must be an ASCII alphanumeric character."), + } + } +} + +struct Map { + antennae: Vec>, + height: usize, + width: usize, +} + +impl TryFrom<&str> for Map { + type Error = ParseError; + + fn try_from(value: &str) -> Result { + let height = value.lines().count(); + if height == 0 { + return Err(Self::Error::EmptyMap); + } + let width = value.lines().next().unwrap().len(); + let mut antennae: Vec> = Vec::new(); + let mut indeces: HashMap = HashMap::new(); + + for (y, line) in value.lines().enumerate() { + if line.len() != width { + return Err(Self::Error::NonRectangular); + } + for (x, c) in line.chars().enumerate() { + match c { + '.' => (), + a if a.is_ascii_alphanumeric() => { + if let Some(idx) = indeces.get(&a) { + antennae[*idx].push((x, y)); + } else { + indeces.insert(a, antennae.len()); + antennae.push(Vec::from([(x, y)])); + } + }, + e => return Err(Self::Error::ParseCharError(e)), + } + } + } + Ok(Self { antennae, height, width, }) + } +} + +impl Map { + fn antinodes_of(&self, (x1, y1): (usize, usize), (x2, y2): (usize, usize)) -> Vec<(usize, usize)> { + let mut res = Vec::new(); + if let (Some(x), Some(y)) = ((2 * x1).checked_sub(x2), (2 * y1).checked_sub(y2)) { + if x < self.width && y < self.height { + res.push((x, y)); + } + } + if let (Some(x), Some(y)) = ((2 * x2).checked_sub(x1), (2 * y2).checked_sub(y1)) { + if x < self.width && y < self.height { + res.push((x, y)); + } + } + res + } + + fn simple_antinodes(&self) -> HashSet<(usize, usize)> { + let mut antinodes = HashSet::new(); + + self.antennae.iter().for_each(|ants| + ants.iter().enumerate().for_each(|(idx1, &a1)| + ants.iter().enumerate().filter(|(idx2, _a2)| *idx2 > idx1).for_each(|(_idx2, &a2)| + self.antinodes_of(a1, a2).iter().for_each(|antinode| { antinodes.insert(*antinode); }) + ))); + + antinodes + } + + fn harmonic_antinodes_of(&self, (x1, y1): (usize, usize), (x2, y2): (usize, usize)) -> Vec<(usize, usize)> { + let mut res = Vec::new(); + for i in 1.. { + if let (Some(x), Some(y)) = ((i*x1).checked_sub((i-1)*x2), (i*y1).checked_sub((i-1)*y2)) { + if x < self.width && y < self.height { + res.push((x, y)); + } else { + break; + } + } else { + break; + } + } + for i in 1.. { + if let (Some(x), Some(y)) = ((i*x2).checked_sub((i-1)*x1), (i*y2).checked_sub((i-1)*y1)) { + if x < self.width && y < self.height { + res.push((x, y)); + } else { + break; + } + } else { + break; + } + } + res + } + + fn antinodes_with_harmonics(&self) -> HashSet<(usize, usize)> { + let mut antinodes = HashSet::new(); + + self.antennae.iter().for_each(|ants| + ants.iter().enumerate().for_each(|(idx1, &a1)| + ants.iter().enumerate().filter(|(idx2, _a2)| *idx2 > idx1).for_each(|(_idx2, &a2)| + self.harmonic_antinodes_of(a1, a2).iter().for_each(|antinode| { antinodes.insert(*antinode); }) + ))); + + antinodes + } +} + +pub fn run(input: &str) -> Result<(usize, usize), ParseError> { + let map = Map::try_from(input)?; + let first = map.simple_antinodes().len(); + let second = map.antinodes_with_harmonics().len(); + Ok((first, second)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs::read_to_string; + + fn read_file(name: &str) -> String { + read_to_string(name).expect(&format!("Unable to read file: {name}")[..]).trim().to_string() + } + + #[test] + fn test_sample() { + let sample_input = read_file("tests/sample_input"); + assert_eq!(run(&sample_input), Ok((14, 34))); + } + + #[test] + fn test_challenge() { + let challenge_input = read_file("tests/challenge_input"); + assert_eq!(run(&challenge_input), Ok((354, 1263))); + } +} diff --git a/2024/day08_resonant_collinearity/tests/challenge_input b/2024/day08_resonant_collinearity/tests/challenge_input new file mode 100644 index 0000000..859a172 --- /dev/null +++ b/2024/day08_resonant_collinearity/tests/challenge_input @@ -0,0 +1,50 @@ +..................................w............... +.................................................. +.....................................C............ +......................................3........... +.............b.......u.........w...........3...... +...........................u...................... +...8........K...........u.......y.........I....... +..................................P5........B..... +...U................2.P...............B...C....... +............i......x.P........w......s.C......IB5. +..............t....................y....x......... +.......8............K....1.......w............u... +.................i.............r.........s........ +..2.............t..T.K.......r......8..........I.. +8..............t..T.....r...................5..... +...2........................1....M.t...N....x..... +...V....U.......................N.S..........I.... +.........W...i............O....v............S..... +................L...1...s.fT.....x............3... +....6.......C...N.........Tf.3.................... +...6.......F..........V..........k...N......H..... +...................U..f........0......H.y......... +.......................O...P......0............... +.......L..U....m.......R............s............. +6...i.................O....0.2.........H.....B.... +........................R......H.........S........ +......F.....c..........m..............d........... +................F.L.....m..................7...... +.............J.........................S.......... +.b....j.k..............V0......................... +.................L.....K.......................... +.......F.......J..............r.....M............. +......................m1....a.R...7............... +.......4......Y..6.D.............................. +k............9.......D................M........... +.....Xb.................V...h..................... +A.........9.Xl..........D......R.................. +4.............c..d........D.............7......... +.A.4.............c.............M.7.v.............. +..........n.9........................h............ +...j....bd.........f.....p..W..................... +.............k.........p.......................... +.......W4.......p......X.....5..J.....v........... +........W.d..c......A........n..v.....o........... +..........l.....n..........o......Y...h........... +.....A............................................ +..j..........n.................................... +a9.lX..................Y...........o.............. +.......a.................Y..........o............. +...a....l.......................p................. diff --git a/2024/day08_resonant_collinearity/tests/sample_input b/2024/day08_resonant_collinearity/tests/sample_input new file mode 100644 index 0000000..78a1e91 --- /dev/null +++ b/2024/day08_resonant_collinearity/tests/sample_input @@ -0,0 +1,12 @@ +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............