From: Greg Burri Date: Mon, 5 Dec 2022 15:13:51 +0000 (+0100) Subject: Simplify and improve performance X-Git-Url: http://git.euphorik.ch/index.cgi?a=commitdiff_plain;h=c5a26fdea838361a6d91516d52b635d00362ef98;p=advent_of_code_2022.git Simplify and improve performance --- 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); } }