This commit is contained in:
2022-12-05 13:02:02 +01:00
parent 15a59bae60
commit 3a6832503c
4 changed files with 854 additions and 2 deletions

View File

@ -1,3 +1,99 @@
fn main() {
println!("Hello, world!");
use std::{fs::read_to_string, str::Lines};
use color_eyre::Result;
use itertools::Itertools;
fn parse_stacks(input: &mut Lines) -> Vec<Vec<char>> {
let horizontal_stack = input
.map(|line| {
line.chars()
.skip(1)
.step_by(4)
.map(|c| if c.is_whitespace() { None } else { Some(c) })
.collect::<Vec<_>>()
})
.take_while(|line| line.first().unwrap_or(&None) != &Some('1'))
.collect::<Vec<_>>();
let num_stacks = horizontal_stack.last().map(|v| v.len()).unwrap_or(0);
let mut vertical_stack: Vec<Vec<char>> = Vec::with_capacity(num_stacks);
for _ in 0..num_stacks {
vertical_stack.push(vec![]);
}
for v in horizontal_stack.iter().rev() {
for (i, c) in v.iter().enumerate() {
if let Some(ch) = c {
vertical_stack[i].push(*ch);
}
}
}
vertical_stack
}
#[derive(Debug, Clone, Copy)]
struct Move {
pub amount: usize,
pub from: usize,
pub to: usize,
}
impl Move {
fn play9000(&self, stacks: &mut [Vec<char>]) {
for _ in 0..self.amount {
if let Some(element) = stacks[self.from].pop() {
stacks[self.to].push(element);
}
}
}
fn play9001(&self, stacks: &mut [Vec<char>]) {
let i = stacks[self.from].len() - self.amount;
let mut moving = stacks[self.from].split_off(i);
stacks[self.to].append(&mut moving);
}
}
fn parse_move(line: &str) -> Move {
let (amount, from, to) = line
.split_whitespace()
.skip(1)
.step_by(2)
.map(|s| s.parse::<usize>().unwrap_or(0))
.take(3)
.collect_tuple()
.unwrap_or((0, 0, 0));
Move {
amount,
from: from - 1,
to: to - 1,
}
}
fn main() -> Result<()> {
let input = read_to_string("input.txt")?;
let mut lines = input.lines();
let mut stacks9000 = parse_stacks(&mut lines);
let mut stacks9001 = stacks9000.clone();
let moves = lines.skip(1).map(parse_move);
for m in moves {
m.play9000(&mut stacks9000);
m.play9001(&mut stacks9001);
}
let top9000 = stacks9000
.iter()
.map(|stack| stack.last().unwrap_or(&' '))
.fold(String::new(), |mut s, v| {
s.push(*v);
s
});
let top9001 = stacks9001
.iter()
.map(|stack| stack.last().unwrap_or(&' '))
.fold(String::new(), |mut s, v| {
s.push(*v);
s
});
println!("top crates 9000: {top9000}");
println!("top crates 9001: {top9001}");
Ok(())
}