AOC2022/rust/5/part1.rs

65 lines
1.8 KiB
Rust

use std::{
fs::File,
io::{BufRead, BufReader},
};
enum State {
Parsing,
Moving,
}
// I hate everything about this
fn main() -> () {
let path = "input.txt";
let input = File::open(path).unwrap();
let buf = BufReader::new(input);
let stack_char_width = 4;
let mut stacks = Vec::<Vec<String>>::new();
let mut state = State::Parsing;
for line in buf.lines() {
let line = line.unwrap();
match state {
State::Parsing => {
if stacks.len() == 0 {
for _ in 0..(line.len() + 1) / stack_char_width {
stacks.push(Vec::new());
}
}
if line != "" {
for i in 0..stacks.len() {
let idx = i * stack_char_width + 1;
let char = &line[idx..idx + 1];
if char != " " {
stacks[i].push(char.to_owned());
}
}
} else {
state = State::Moving;
for stack in &mut stacks {
stack.pop();
stack.reverse();
}
}
}
State::Moving => {
let tokens = line
.split(' ')
.filter_map(|tok| tok.parse::<usize>().ok())
.collect::<Vec<_>>();
for _ in 0..tokens[0] {
let tmp = stacks[tokens[1] - 1].pop().unwrap();
stacks[tokens[2] - 1].push(tmp);
}
}
};
}
println!(
"{}",
stacks.into_iter().fold(String::from(""), |acc, mut stack| {
acc + &stack.pop().unwrap()
})
);
}