From d88886869a192a0c0b96b8c5b003e8b4d6fb29c5 Mon Sep 17 00:00:00 2001 From: Vivianne Langdon Date: Thu, 8 Dec 2022 01:29:54 -0800 Subject: [PATCH] Second star. Too lazy to figure out proper cloning of the Dock so we just parse it twice, whatever --- src/bin/p05.rs | 64 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/src/bin/p05.rs b/src/bin/p05.rs index 6d5deec..5ccf77b 100644 --- a/src/bin/p05.rs +++ b/src/bin/p05.rs @@ -50,27 +50,58 @@ impl FromStr for CrateStack { #[derive(Debug)] struct Dock(Vec); +trait Crane { + fn run_directive(dock: &mut Dock, directive: &MoveDirective) -> bool; +} + impl Dock { - fn perform_directive(&mut self, directive: &MoveDirective) -> bool { - if directive.source >= self.0.len() { + fn tops(&self) -> impl Iterator> { + self.0.iter().map(|s| s.0.iter().last()) + } +} + +struct CrateMover9000; + +impl Crane for CrateMover9000 { + fn run_directive(dock: &mut Dock, directive: &MoveDirective) -> bool { + if directive.source >= dock.0.len() { return false; } - if directive.dest >= self.0.len() { + if directive.dest >= dock.0.len() { return false; } for _ in 0..directive.number { - if let Some(s) = self.0[directive.source].pop() { - self.0[directive.dest].push(s) + if let Some(s) = dock.0[directive.source].pop() { + dock.0[directive.dest].push(s) } } true } +} - fn tops(&self) -> impl Iterator> { - self.0.iter().map(|s| s.0.iter().last()) +struct CrateMover9001; + +impl Crane for CrateMover9001 { + fn run_directive(dock: &mut Dock, directive: &MoveDirective) -> bool { + if directive.source >= dock.0.len() { + return false; + } + + if directive.dest >= dock.0.len() { + return false; + } + + let source_vec = &mut dock.0[directive.source].0; + + let drained: Vec = source_vec + .drain((source_vec.len() - usize::try_from(directive.number).unwrap())..) + .collect(); + dock.0[directive.dest].0.extend(drained); + + true } } @@ -158,20 +189,29 @@ fn main() { println!("PART ONE ---------------"); part1(dock, &moves); + let dock2: Dock = string + .split("\n\n") + .next() + .expect("first section") + .parse::() + .expect("can't parse dock"); + println!("\n PART TWO ---------------"); + part2(dock2, &moves); } fn part1(mut dock: Dock, moves: &[MoveDirective]) { for m in moves { - dock.perform_directive(m); + CrateMover9000::run_directive(&mut dock, m); } dbg!(dock.tops().flatten().map(|c| c.0).collect::()); } -fn part2() {} +fn part2(mut dock: Dock, moves: &[MoveDirective]) { + for m in moves { + CrateMover9001::run_directive(&mut dock, m); + } -#[cfg(test)] -mod tests { - use super::*; + dbg!(dock.tops().flatten().map(|c| c.0).collect::()); }