From 4c4f765dd454660726c1608a8328afd7a08939f1 Mon Sep 17 00:00:00 2001 From: Christian Ulrich Date: Tue, 6 Dec 2022 00:15:40 +0100 Subject: [PATCH] add day 5, part 2 --- day05/common.rs | 13 +++++++++++++ day05/part2.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 day05/part2.rs diff --git a/day05/common.rs b/day05/common.rs index facbef5..cf4b9b1 100644 --- a/day05/common.rs +++ b/day05/common.rs @@ -98,6 +98,19 @@ impl Stacks { } Ok(()) } + + pub fn move_items_retain_order(&mut self, spec: Move) -> Result<(), &'static str> { + if spec.from >= self.inner.len() + || spec.to >= self.inner.len() + || spec.count > self.inner[spec.from].len() + { + return Err("invalid move"); + } + let split_index = self.inner[spec.from].len() - spec.count; + let mut items = self.inner[spec.from].split_off(split_index); + self.inner[spec.to].append(&mut items); + Ok(()) + } } impl Iterator for Stacks { diff --git a/day05/part2.rs b/day05/part2.rs new file mode 100644 index 0000000..f14ee92 --- /dev/null +++ b/day05/part2.rs @@ -0,0 +1,32 @@ +// Copyright 2022 Christian Ulrich +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// usage: ./part2 < input + +pub mod common; + +use common::{Moves, Stacks}; + +fn main() -> Result<(), &'static str> { + let mut stacks = Stacks::from_stdin()?; + for op in Moves::from_stdin() { + stacks.move_items_retain_order(op?)?; + } + let result: Result = stacks + .map(|s| s.last().cloned().ok_or("at least one stack is empty")) + .collect(); + println!("{}", result?); + Ok(()) +}