From 72426e9163603167bf27f7e4fcdf1947c625ac47 Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Sun, 11 Dec 2022 00:46:28 -0500 Subject: [PATCH] Finish day 5 --- 2022/src/day5.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/2022/src/day5.rs b/2022/src/day5.rs index 72358cd..202ff52 100644 --- a/2022/src/day5.rs +++ b/2022/src/day5.rs @@ -16,7 +16,8 @@ pub fn part1() -> String { } pub fn part2() -> String { - unimplemented!() + let (stacks, commands) = input(INPUT); + tops(run_commands_multicrate(stacks, commands)) } fn run_commands(stacks: Stacks, commands: Vec) -> Stacks { @@ -25,6 +26,12 @@ fn run_commands(stacks: Stacks, commands: Vec) -> Stacks { .fold(stacks, |stacks, command| stacks.run_command(command)) } +fn run_commands_multicrate(stacks: Stacks, commands: Vec) -> Stacks { + commands.into_iter().fold(stacks, |stacks, command| { + stacks.run_command_multicrate(command) + }) +} + fn tops(stacks: Stacks) -> String { stacks .0 @@ -125,6 +132,25 @@ impl Stacks { }); self } + + fn run_command_multicrate(mut self, cmd: Command) -> Self { + let Command { + count, + source, + dest, + } = cmd; + + let mut stack = Vec::new(); + (0..count).for_each(|_| { + let val = self.0[(source - 1) as usize].pop().unwrap(); + stack.push(val); + }); + while stack.len() > 0 { + self.0[(dest - 1) as usize].push(stack.pop().unwrap()); + } + + self + } } fn input(data: &str) -> (Stacks, Vec) { @@ -263,6 +289,23 @@ move 1 from 1 to 2"; }); } + #[test] + fn it_can_follow_multicrate_commands() { + with_input(|(stacks, commands)| { + let stacks = stacks.run_command_multicrate(commands[0].clone()); + assert_eq!(stacks.0[0].0, vec!['Z', 'N', 'D']); + assert_eq!(stacks.0[1].0, vec!['M', 'C']); + assert_eq!(stacks.0[2].0, vec!['P']); + }); + + with_input(|(stacks, commands)| { + let stacks = run_commands_multicrate(stacks, commands); + assert_eq!(stacks.0[0].0, vec!['M']); + assert_eq!(stacks.0[1].0, vec!['C']); + assert_eq!(stacks.0[2].0, vec!['P', 'Z', 'N', 'D']); + }); + } + #[test] fn it_can_find_tops() { with_input(|(stacks, commands)| {