use std::collections::{HashMap, VecDeque}; use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; #[derive(Debug)] struct Instruction { n: usize, from: usize, to: usize, } fn run_machine(stacks: &mut [VecDeque], instructions: &[Instruction]) { for inst in instructions { for _ in 0..inst.n { let moving = stacks[inst.from].pop_front().unwrap(); stacks[inst.to].push_front(moving); } } } fn run_machine2(stacks: &mut [VecDeque], instructions: &[Instruction]) { for inst in instructions { let mut moving = stacks[inst.from].split_off(inst.n); // semantics of split_off are opposite of what we want std::mem::swap(&mut moving, &mut stacks[inst.from]); moving.append(&mut stacks[inst.to]); stacks[inst.to] = moving; } } #[aoc_generator(day5)] fn parse(input: &str) -> (Vec>, Vec) { enum State { Stacks, Ids, Instructions, } let mut stacks = HashMap::new(); let mut instructions = Vec::new(); let mut state = State::Stacks; for line in input.lines() { match state { State::Stacks => { for (stack, top) in line.as_bytes().chunks(4).map(|s| s[1]).enumerate() { if top.is_ascii_digit() { state = State::Ids } else if top != b' ' { stacks.entry(stack).or_insert(VecDeque::new()).push_back(top); } } } State::Ids => { if line.is_empty() { state = State::Instructions } } State::Instructions => { let tokens = line.split_ascii_whitespace().collect_vec(); instructions.push(Instruction { n: tokens[1].parse::().unwrap(), from: tokens[3].parse::().unwrap() - 1, to: tokens[5].parse::().unwrap() - 1, }) } } } ( stacks .iter() .sorted_by_key(|(k, _v)| **k) .map(|(_k, v)| v.clone()) .collect_vec(), instructions, ) } #[aoc(day5, part1)] fn part1((stacks, instructions): &(Vec>, Vec)) -> String { let mut stacks = stacks.clone(); run_machine(&mut stacks, instructions); stacks.iter().map(|s| *s.front().unwrap() as char).join("") } #[aoc(day5, part2)] fn part2((stacks, instructions): &(Vec>, Vec)) -> String { let mut stacks = stacks.clone(); run_machine2(&mut stacks, instructions); stacks.iter().map(|s| *s.front().unwrap() as char).join("") } #[cfg(test)] mod tests { use super::*; const EXAMPLE: &str = " [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2"; #[test] fn part1_example() { assert_eq!(part1(&parse(EXAMPLE)), "CMZ"); } #[test] fn part2_example() { assert_eq!(part2(&parse(EXAMPLE)), "MCD"); } }