From 000001801f0a895849fc24e7c63da30676c6aed7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Jane=C5=BEi=C4=8D?= Date: Sun, 15 Dec 2024 00:11:58 +0100 Subject: [PATCH] solution: day 14 --- data/examples/14.txt | 12 +++++ src/bin/14.rs | 107 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 data/examples/14.txt create mode 100644 src/bin/14.rs diff --git a/data/examples/14.txt b/data/examples/14.txt new file mode 100644 index 000000000..2455da4 --- /dev/null +++ b/data/examples/14.txt @@ -0,0 +1,12 @@ +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 diff --git a/src/bin/14.rs b/src/bin/14.rs new file mode 100644 index 000000000..bf191d5 --- /dev/null +++ b/src/bin/14.rs @@ -0,0 +1,107 @@ +use hashbrown::HashMap; +use num_integer::Integer; +use regex::Regex; + +fn parse_input(input: &str) -> Vec<((isize, isize), (isize, isize))> { + let r = Regex::new(r"p=(\d+),(\d+) v=(-?\d+),(-?\d+)").unwrap(); + + let mut parsed = Vec::new(); + + for line in input.lines() { + let c = r.captures(line).unwrap(); + let j: isize = c.get(1).unwrap().as_str().parse().unwrap(); + let i: isize = c.get(2).unwrap().as_str().parse().unwrap(); + let y: isize = c.get(3).unwrap().as_str().parse().unwrap(); + let x: isize = c.get(4).unwrap().as_str().parse().unwrap(); + + parsed.push(((i, j), (x, y))); + } + + parsed +} + +pub fn part_one(input: &str) -> Option { + let parsed = parse_input(input); + let mut r = [0; 4]; + + let h = 103; + let w = 101; + + for ((pi, pj), (vi, vj)) in parsed { + let ni = (pi + vi * 100).rem_euclid(h); + let nj = (pj + vj * 100).rem_euclid(w); + + if ni < h / 2 && nj > w / 2 { + r[0] += 1; + } + + if ni < h / 2 && nj < w / 2 { + r[1] += 1; + } + + if ni > h / 2 && nj < w / 2 { + r[2] += 1; + } + + if ni > h / 2 && nj > w / 2 { + r[3] += 1; + } + } + + r.into_iter().product::().into() +} + +pub fn part_two(input: &str) -> Option { + let pv = parse_input(input); + + let h = 103; + let w = 101; + + let mut n = 1; + + // hardcoded side lengths of the "easter egg" + let th = 33; + let tw = 31; + + for ((pi, pj), (vi, vj)) in pv.iter().copied() { + let mut m = 1; + + loop { + let ni = (pi + vi * m).rem_euclid(h); + let nj = (pj + vj * m).rem_euclid(w); + if (ni, nj) == (pi, pj) { + break; + } + m += 1; + } + + n = n.lcm(&m); + } + + let mut sh = HashMap::new(); + let mut sw = HashMap::new(); + + for m in 0..n { + sh.clear(); + sw.clear(); + + for ((pi, pj), (vi, vj)) in pv.iter().copied() { + let ni = (pi + vi * m).rem_euclid(h); + let nj = (pj + vj * m).rem_euclid(w); + + *sw.entry(ni).or_default() += 1_usize; + *sh.entry(nj).or_default() += 1_usize; + } + + let ch = sh.values().filter(|&&x: &&usize| x >= th).count(); + let cw = sw.values().filter(|&&x: &&usize| x >= tw).count(); + + if ch >= 2 && cw >= 2 { + return Some(n as usize); + } + } + + None +} + +aoc::solution!(14);