dumb_shit/2022-aoc/src/d5.rs

87 lines
2.4 KiB
Rust
Raw Normal View History

2022-12-05 23:33:13 +00:00
use aoc_runner_derive::{aoc as aoc_run, aoc_generator};
type Stax = Vec<Vec<char>>;
2022-12-06 00:46:17 +00:00
type Inst = (usize, usize, usize);
2022-12-05 23:33:13 +00:00
#[aoc_generator(day5)]
fn parse_input_day1(input: &str) -> (Stax, Vec<Inst>) {
let mut out = Vec::new();
let mut inst = Vec::new();
2022-12-06 22:55:16 +00:00
let mut parsing_crates = true;
2022-12-05 23:33:13 +00:00
for _ in 0..9 {
out.push(Vec::new());
}
let re = regex::Regex::new(r"^move (\d+) from (\d+) to (\d+)$").unwrap();
for line in input.lines() {
2022-12-06 22:55:16 +00:00
if parsing_crates {
if line.trim().starts_with('1') {
continue;
2022-12-05 23:33:13 +00:00
}
2022-12-06 22:55:16 +00:00
if line.trim().is_empty() {
parsing_crates = false;
2022-12-05 23:33:13 +00:00
}
2022-12-06 22:55:16 +00:00
for (i, cell) in line.as_bytes().chunks(4).enumerate() {
let cell = std::str::from_utf8(cell).unwrap().trim();
if !cell.is_empty() {
let cell = cell.strip_prefix('[').unwrap().strip_suffix(']').unwrap();
out[i].push(cell.chars().next().unwrap());
}
}
} else {
let ins = re.captures(line).unwrap();
inst.push((
ins[1].parse().unwrap(),
ins[2].parse::<usize>().unwrap() - 1,
ins[3].parse::<usize>().unwrap() - 1,
));
2022-12-05 23:33:13 +00:00
}
}
2022-12-06 22:55:16 +00:00
2022-12-05 23:33:13 +00:00
for stack in out.iter_mut() {
stack.reverse();
}
(out, inst)
}
#[aoc_run(day5, part1)]
fn part1((stax, inst): &(Stax, Vec<Inst>)) -> String {
let mut stax = stax.to_owned();
for ins in inst.iter() {
let (amt, from, to) = ins;
2022-12-06 00:46:17 +00:00
let from = &mut stax[*from];
let mut tmp = Vec::with_capacity(*amt);
2022-12-05 23:33:13 +00:00
for _ in 0..*amt {
let t = from.pop().unwrap();
tmp.push(t);
}
2022-12-06 00:46:17 +00:00
stax[*to].append(&mut tmp);
2022-12-05 23:33:13 +00:00
}
let mut s = String::with_capacity(9);
for stack in stax {
s.push(stack.last().copied().unwrap());
}
s
}
#[aoc_run(day5, part2)]
2022-12-06 00:46:17 +00:00
fn p2((stax, inst): &(Stax, Vec<Inst>)) -> String {
let mut stax = stax.to_owned();
for ins in inst.iter() {
let (amt, from, to) = ins;
let from = &mut stax[*from];
let mut tmp = Vec::with_capacity(*amt);
for _ in 0..*amt {
let c = from.pop().unwrap();
tmp.push(c);
}
2022-12-06 22:55:16 +00:00
tmp.reverse();
stax[*to].append(&mut tmp);
2022-12-06 00:46:17 +00:00
}
let mut s = String::with_capacity(9);
for stack in stax {
s.push(stack.last().copied().unwrap());
}
s
2022-12-05 23:33:13 +00:00
}