use anyhow::Result; use std::fs; pub fn run() -> Result<()> { #[cfg(not(feature = "test_input"))] let file_contents = fs::read_to_string("day5.txt")?; #[cfg(feature = "test_input")] let file_contents = fs::read_to_string("tests/day5.txt")?; let mut stacks: Vec> = Vec::with_capacity(10); let mut moves: Vec<(usize, usize, usize)> = Vec::with_capacity(1000); let mut numstacks: usize = 0; let mut containers: Vec<&str> = Vec::with_capacity(20); for line in file_contents.lines() { if line.contains('[') { containers.push(line); } else { for stacknums in line.split(' ') { if let Ok(num) = stacknums.parse::() { numstacks = num; stacks.push(Vec::with_capacity(100)) } } println!("found {} numstacks", numstacks); break; } } for line in containers.into_iter() { for index in 0..numstacks { let col = index * 4 + 1; let t = &line[col..col + 1]; if t != " " { stacks[index].insert(0, t); } } } for line in file_contents.lines() { if !line.contains("move") { continue; } let mut tokens = line.split(' '); let count = tokens.nth(1).expect("missing count").parse::()?; let from = tokens.nth(1).expect("missing from").parse::()?; let to = tokens.nth(1).expect("missing to").parse::()?; moves.push((count, from, to)); } let mut stacks2 = stacks.clone(); for (count, from, to) in moves.iter() { for _x in 0..*count { let c = stacks[from - 1].pop().expect("too many pops"); stacks[to - 1].push(c); } } let final_message = stacks .iter() .map(|e| e[e.len() - 1]) .collect::>() .join(""); println!("final {}", final_message); for (count, from, to) in moves.iter() { let x = stacks2[to - 1].len(); for _ in 0..*count { let c = stacks2[from - 1].pop().expect("too many pops"); stacks2[to - 1].insert(x, c); } } let second_message = stacks2 .iter() .map(|e| e[e.len() - 1]) .collect::>() .join(""); println!("second message {}", second_message); Ok(()) }