From 505ea3771a80da355d60235a2ca9e81307f5eba3 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Thu, 14 Dec 2023 18:19:21 +0000 Subject: [PATCH] Day 14 Part 2 Complete -> First solution took agest to run but added the hashmap to detect cycles in the rotations. Thanks reddit :) --- src/solutions/day14.rs | 57 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/src/solutions/day14.rs b/src/solutions/day14.rs index 40c4f5f..9d3a392 100644 --- a/src/solutions/day14.rs +++ b/src/solutions/day14.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use super::Solution; pub struct Day14 {} @@ -19,9 +21,28 @@ impl Solution for Day14 { fn part2( &self, - _input: &mut Vec, + input: &mut Vec, ) -> Result, Box> { - Ok(Box::new("Ready")) + let mut rock_formation = input + .iter() + .map(|r| r.chars().collect::>()) + .collect::>(); + + let mut rotations: HashMap>, usize> = HashMap::new(); + for i in 1..=1_000_000_000 { + for _ in 0..4 { + self.pull_north(&mut rock_formation); + rock_formation = self.rotate(&rock_formation); + } + + if let Some(rotation) = rotations.insert(rock_formation.clone(), i) { + if (1_000_000_000 - i) % (i - rotation) == 0 { + break; + } + } + } + + Ok(Box::new(self.get_load(&rock_formation))) } fn get_day(&self) -> u8 { @@ -59,6 +80,17 @@ impl Day14 { }) .sum::() as u32 } + + // Function that rotates the given vector through 90 degrees clockwise + fn rotate(&self, cave: &Vec>) -> Vec> { + let mut new_cave = vec![vec![' '; cave.len()]; cave[0].len()]; + for row in 0..cave.len() { + for col in 0..cave[0].len() { + new_cave[col][cave.len() - row - 1] = cave[row][col]; + } + } + new_cave + } } /// Test from puzzle input @@ -98,6 +130,25 @@ mod test { .unwrap() .to_string(); - assert_eq!(answer, "Ready"); + assert_eq!(answer, "64"); + } + + #[test] + fn rotation_test() { + let challenge = day14::Day14 {}; + + let mut arr = vec![ + vec!['a', 'b', 'c', 'd'], + vec!['d', 'e', 'f', 'g'], + vec!['h', 'i', 'j', 'k'], + vec!['l', 'm', 'n', 'o'], + ]; + + let ans = arr.clone(); + for _ in 0..4 { + arr = challenge.rotate(&arr); + } + + assert_eq!(arr, ans); } }