add day 5, part 2

This commit is contained in:
Christian Ulrich 2022-12-06 00:15:40 +01:00
parent a4a73c712b
commit 4c4f765dd4
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
2 changed files with 45 additions and 0 deletions

View File

@ -98,6 +98,19 @@ impl Stacks {
} }
Ok(()) 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 { impl Iterator for Stacks {

32
day05/part2.rs Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
//
// 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<String, _> = stacks
.map(|s| s.last().cloned().ok_or("at least one stack is empty"))
.collect();
println!("{}", result?);
Ok(())
}