1
0
Fork 0
advent-of-code/2022/src/days/day5.rs

86 lines
2.4 KiB
Rust
Raw Normal View History

2022-12-05 10:54:06 -05:00
use anyhow::Result;
use std::fs;
pub fn run() -> Result<()> {
2022-12-07 14:16:10 -05:00
#[cfg(not(feature = "test_input"))]
2022-12-05 10:54:06 -05:00
let file_contents = fs::read_to_string("day5.txt")?;
2022-12-07 14:16:10 -05:00
#[cfg(feature = "test_input")]
let file_contents = fs::read_to_string("tests/day5.txt")?;
2022-12-05 10:54:06 -05:00
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() {
2022-12-08 12:30:57 -05:00
if line.contains('[') {
2022-12-05 10:54:06 -05:00
containers.push(line);
} else {
2022-12-08 12:30:57 -05:00
for stacknums in line.split(' ') {
2022-12-05 10:54:06 -05:00
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;
}
2022-12-08 12:30:57 -05:00
let mut tokens = line.split(' ');
2022-12-05 10:54:06 -05:00
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(())
}