day 5. most of the work here was getting the parsing right

This commit is contained in:
David 2022-12-05 08:35:47 -05:00
parent c875ec5826
commit b0f72b2230

115
05/main.rs Normal file
View File

@ -0,0 +1,115 @@
#![allow(dead_code)]
use std::collections::VecDeque;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::path::Path;
use std::time::Instant;
fn main() {
let now = Instant::now();
part_one();
let part_one_duration = now.elapsed();
part_two();
let part_two_duration = now.elapsed();
println!(
"p1: {}ms, p2: {}ms",
part_one_duration.as_millis(),
(part_two_duration - part_one_duration).as_millis()
);
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
// note that this discards a final newline
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn part_one() {
if let Ok(lines) = read_lines("./inputs/input") {
let mut stacks = vec![VecDeque::<char>::new(); 9];
let mut lines_parsed = 0;
for line in lines {
lines_parsed += 1;
// build our stacks...
if lines_parsed < 9 {
if let Ok(stack) = line {
for (i, s) in stack.chars().enumerate() {
if (i % 4) == 1 && s != ' ' {
// we load in from the head, so the end of the vec is the "top" of the stack
stacks[(i / 4)].push_front(s)
}
}
continue;
}
}
if lines_parsed < 11 {
continue; // skip the break
}
// ok, so now we need to move the crates around
if let Ok(instruction) = line {
let steps = instruction.split(" ").collect::<Vec<&str>>();
let (mut count, from, to) = (
steps[1].parse::<usize>().unwrap(),
steps[3].parse::<usize>().unwrap(),
steps[5].parse::<usize>().unwrap(),
);
while count > 0 {
let c = stacks[from - 1].pop_back().unwrap();
stacks[to - 1].push_back(c);
count -= 1;
}
}
}
let mut result = "".to_string();
for mut s in stacks {
result.push(s.pop_back().unwrap());
}
println!("{}", result);
}
}
fn part_two() {
if let Ok(lines) = read_lines("./inputs/input") {
let mut stacks = vec![VecDeque::<char>::new(); 9];
let mut lines_parsed = 0;
for line in lines {
lines_parsed += 1;
// build our stacks...
if lines_parsed < 9 {
if let Ok(stack) = line {
for (i, s) in stack.chars().enumerate() {
if (i % 4) == 1 && s != ' ' {
// we load in from the head, so the end of the vec is the "top" of the stack
stacks[(i / 4)].push_front(s)
}
}
continue;
}
}
if lines_parsed < 11 {
continue; // skip the break
}
// ok, so now we need to move the crates around
if let Ok(instruction) = line {
let steps = instruction.split(" ").collect::<Vec<&str>>();
let (count, from, to) = (
steps[1].parse::<usize>().unwrap(),
steps[3].parse::<usize>().unwrap(),
steps[5].parse::<usize>().unwrap(),
);
let s = stacks[from - 1].len();
let mut c = stacks[from - 1].split_off(s - count);
stacks[to - 1].append(&mut c);
}
}
let mut result = "".to_string();
for mut s in stacks {
result.push(s.pop_back().unwrap());
}
println!("{}", result);
}
}