2022-12-18 18:26:03 +01:00
|
|
|
use std::error;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::io::BufRead;
|
|
|
|
use std::io::BufReader;
|
|
|
|
|
|
|
|
use regex::Regex;
|
|
|
|
|
|
|
|
fn main() -> Result<(), Box<dyn error::Error>> {
|
|
|
|
let f = File::open("input.txt")?;
|
|
|
|
let reader = BufReader::new(f);
|
|
|
|
|
|
|
|
let mut lines = reader.lines();
|
|
|
|
|
|
|
|
let mut items: Vec<Vec<&str>> = Vec::new();
|
|
|
|
|
|
|
|
// read the initial state
|
|
|
|
let mut init_lines: Vec<String> = 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<usize> = re.captures(&line).ok_or("Could not match line")?.iter().skip(1).map(|x| x.unwrap().as_str().parse().unwrap()).collect();
|
2022-12-18 18:31:23 +01:00
|
|
|
let mut items_to_move = vec![];
|
2022-12-18 18:26:03 +01:00
|
|
|
for _ in 0..cap[0] {
|
|
|
|
let item = items[cap[1] - 1].pop().ok_or("Found a broken match")?;
|
2022-12-18 18:31:23 +01:00
|
|
|
items_to_move.push(item);
|
|
|
|
}
|
|
|
|
|
|
|
|
for item in items_to_move.iter().rev() {
|
2022-12-18 18:26:03 +01:00
|
|
|
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::<Vec<_>>().join(""));
|
|
|
|
Ok(())
|
|
|
|
}
|