From 88af3ba2e144cd7942bf00ede5a672b94c4d3ce9 Mon Sep 17 00:00:00 2001 From: ictrobot Date: Mon, 28 Oct 2024 17:54:18 +0000 Subject: [PATCH] 2017 day 6 --- crates/year2017/src/day06.rs | 84 ++++++++++++++++++++++++++++++++++++ crates/year2017/src/lib.rs | 1 + 2 files changed, 85 insertions(+) create mode 100644 crates/year2017/src/day06.rs diff --git a/crates/year2017/src/day06.rs b/crates/year2017/src/day06.rs new file mode 100644 index 0000000..cefbb2c --- /dev/null +++ b/crates/year2017/src/day06.rs @@ -0,0 +1,84 @@ +use utils::prelude::*; + +/// Finding cycles. +/// +/// See , which avoids storing and +/// hashing every visited state at the expense of calculating extra iterations. +#[derive(Clone, Debug)] +pub struct Day06 { + part1: u32, + part2: u32, +} + +impl Day06 { + pub fn new(input: &str, _: InputType) -> Result { + let banks = parser::u32() + .with_suffix(b' '.or(b'\t').optional()) + .parse_all(input)?; + + let (mut power, mut lambda) = (1, 1); + let mut tortoise = banks.clone(); + let mut hare = banks.clone(); + Self::next(&mut hare); + + while tortoise != hare { + if power == lambda { + tortoise.copy_from_slice(hare.as_slice()); + power *= 2; + lambda = 0; + } + Self::next(&mut hare); + lambda += 1; + } + + tortoise.copy_from_slice(banks.as_slice()); + hare.copy_from_slice(banks.as_slice()); + for _ in 0..lambda { + Self::next(&mut hare); + } + + let mut mu = 0; + while tortoise != hare { + Self::next(&mut tortoise); + Self::next(&mut hare); + mu += 1; + } + + Ok(Self { + part1: mu + lambda, + part2: lambda, + }) + } + + fn next(banks: &mut [u32]) { + let (mut idx, mut remaining) = banks + .iter() + .copied() + .enumerate() + .rev() + .max_by_key(|&(_, v)| v) + .unwrap(); + + banks[idx] = 0; + + while remaining > 0 { + idx = (idx + 1) % banks.len(); + banks[idx] += 1; + remaining -= 1; + } + } + + #[must_use] + pub fn part1(&self) -> u32 { + self.part1 + } + + #[must_use] + pub fn part2(&self) -> u32 { + self.part2 + } +} + +examples!(Day06 -> (u32, u32) [ + {input: "0\t2\t7\t0", part1: 5, part2: 4}, +]); diff --git a/crates/year2017/src/lib.rs b/crates/year2017/src/lib.rs index 14824d5..33c1e32 100644 --- a/crates/year2017/src/lib.rs +++ b/crates/year2017/src/lib.rs @@ -7,4 +7,5 @@ utils::year!(2017 => year2017, ${ 3 => day03::Day03, 4 => day04::Day04<'_>, 5 => day05::Day05, + 6 => day06::Day06, });