use std::error; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use regex::Regex; fn main() -> Result<(), Box> { let f = File::open("input.txt")?; let reader = BufReader::new(f); let mut lines = reader.lines(); let mut items: Vec> = Vec::new(); // read the initial state let mut init_lines: Vec = vec![]; while let Some(Ok(line)) = lines.next() { if line == "" { break; } init_lines.push(line); } init_lines.reverse(); let mut count = 0; for (i, line) in init_lines.iter().enumerate() { // init the items with the right amount of Vecs if i == 0 { count = line.split_whitespace().count(); for _ in 0..count { items.push(vec![]); } continue; } // add the items to the vecs // let line_iter = line.chars(); for i in 0..count { let item = &line[(i * 4 + 1)..(i * 4 + 2)]; if item == " " { continue; } items[i].push(&item); } } // read the movements let re = Regex::new(r"^move (\d+) from (\d+) to (\d+)$")?; while let Some(Ok(line)) = lines.next() { // println!("{:?}", re.captures(&line)); // println!("{:?}", items); let cap: Vec = re.captures(&line).ok_or("Could not match line")?.iter().skip(1).map(|x| x.unwrap().as_str().parse().unwrap()).collect(); let mut items_to_move = vec![]; for _ in 0..cap[0] { let item = items[cap[1] - 1].pop().ok_or("Found a broken match")?; items_to_move.push(item); } for item in items_to_move.iter().rev() { items[cap[2] - 1].push(item); } } // output the result (top of each item-stack i.e. end of the Vec) // println!("{:?}", items); println!("{}", items.iter().map(|v| String::from(*v.iter().last().unwrap())).collect::>().join("")); Ok(()) }