day5.rs (2481B)
1 use std::{collections::HashMap}; 2 use regex::Regex; 3 4 pub fn run(input: String) { 5 let lines: Vec<&str> = input.lines().collect(); 6 let mut lix: usize = 0; 7 let mut ship: HashMap<usize, Vec<char>> = HashMap::new(); 8 for line in lines.iter() { 9 lix += 1; 10 let chrs: Vec<char> = line.chars().collect(); 11 // Line with just container numbers after the containers themselves 12 if chrs[1] == '1' { 13 break; 14 } 15 for (ix, container) in chrs.chunks(4).enumerate() { 16 let stack = ship.entry(ix+1).or_insert(Vec::new());// key starts at 1, of course 17 let payload = container[1]; 18 if payload.is_alphabetic() { 19 stack.insert(0, payload) // last one we found is always the bottom of the stack 20 } 21 } 22 } 23 //println!("ship: {:?}", ship); 24 lix += 1; 25 26 27 let re = Regex::new(r"^move (\d+) from (\d+) to (\d+)$").unwrap(); 28 assert!(re.is_match("move 1 from 2 to 4")); 29 for line in lines[lix..].iter() { 30 // parse the instruction... 31 // "move 1 from 2 to 1" 32 33 let mm = re.captures(line).expect("instruction didn't match regex???"); 34 let n: usize = mm.get(1).unwrap().as_str().parse().unwrap(); 35 let ifrom: usize = mm.get(2).unwrap().as_str().parse().unwrap(); 36 let ito: usize = mm.get(3).unwrap().as_str().parse().unwrap(); 37 //println!("moving {} from {} to {}", n, ifrom, ito); 38 // for _ in 0..n { 39 // let stackfrom = ship.get_mut(&ifrom).expect("couldn't find stack to pop from!"); 40 // let ch = stackfrom.pop().expect("failed to pop from stack! maybe it was empty?"); 41 // let stackto = ship.get_mut(&ito).expect("couldn't find stack to push to!"); 42 // stackto.push(ch); 43 // } 44 let stackfrom = ship.get_mut(&ifrom).expect("couldn't find stack to pop from!"); 45 let mut chunk: Vec<char> = Vec::new(); 46 for _ in 0..n { 47 let ch = stackfrom.pop().expect("failed to pop from stack! maybe it was empty?"); 48 chunk.push(ch); 49 } 50 let stackto = ship.get_mut(&ito).expect("couldn't find stack to push to!"); 51 for _ in 0..n { 52 let ch = chunk.pop().unwrap(); 53 stackto.push(ch); 54 } 55 } 56 57 print!("day 5: "); 58 for i in 1..(ship.keys().len()+1) { 59 let topch = ship.get(&i).unwrap().last().unwrap(); 60 print!("{}", topch); 61 } 62 print!("\n"); 63 64 65 }