81 lines
2.3 KiB
Rust
81 lines
2.3 KiB
Rust
|
use anyhow::Result;
|
||
|
use std::fs;
|
||
|
|
||
|
pub fn run() -> Result<()> {
|
||
|
let file_contents = fs::read_to_string("day5.txt")?;
|
||
|
let mut stacks: Vec<Vec<&str>> = 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::<usize>() {
|
||
|
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::<usize>()?;
|
||
|
let from = tokens.nth(1).expect("missing from").parse::<usize>()?;
|
||
|
let to = tokens.nth(1).expect("missing to").parse::<usize>()?;
|
||
|
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::<Vec<&str>>()
|
||
|
.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::<Vec<&str>>()
|
||
|
.join("");
|
||
|
println!("second message {}", second_message);
|
||
|
|
||
|
Ok(())
|
||
|
}
|