From ec95faf33714bd0b131dad2a98a4695ec5dcc086 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Mon, 5 Dec 2022 16:13:51 +0100 Subject: [PATCH] Simplify and improve performance --- src/day05.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/day05.rs b/src/day05.rs index 5e9daff..e727784 100644 --- a/src/day05.rs +++ b/src/day05.rs @@ -44,21 +44,22 @@ pub fn parse(s: &str) -> (Stacks, Vec) { } pub fn apply_moves_by_crate_mover_9000(stacks: &mut Stacks, moves: &[Move]) { - for m in moves { - for _ in 0..m.n { - if let Some(c) = stacks[m.from].pop_back() { - stacks[m.to].push_back(c); - } else { - break; - } - } - } + apply_moves(stacks, moves, true); } pub fn apply_moves_by_crate_mover_9001(stacks: &mut Stacks, moves: &[Move]) { + apply_moves(stacks, moves, false); +} + +fn apply_moves(stacks: &mut Stacks, moves: &[Move], reverse_stack: bool) { for m in moves { let from = stacks.get_mut(m.from).unwrap(); let mut to_move = from.split_off(from.len() - m.n); + + if reverse_stack { + to_move.make_contiguous().reverse(); + } + stacks[m.to].append(&mut to_move); } } -- 2.45.2