-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday05.rs
87 lines (75 loc) · 2.39 KB
/
day05.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::collections::VecDeque;
use crate::utils::v2::solver;
use itertools::Itertools;
use scan_fmt::scan_fmt;
struct Instruction {
qty: usize,
from: usize,
to: usize,
}
pub struct Solver;
impl Solver {
fn parse(input: &str) -> (Vec<VecDeque<char>>, impl Iterator<Item = Instruction> + '_) {
let (crates, instructions) = input.split("\n\n").into_iter().collect_tuple().unwrap();
let crates = crates
.lines()
.flat_map(|l| {
l.chars()
.skip(1)
.step_by(4)
.enumerate()
.filter(|(_, c)| c.is_alphabetic())
})
.into_grouping_map()
.collect::<VecDeque<char>>();
let crates = crates
.into_iter()
.sorted_by_key(|(i, _)| *i)
.map(|(_, stack)| stack)
.collect();
let instructions = instructions
.lines()
.filter_map(|l| scan_fmt!(l, "move {d} from {d} to {d}", usize, usize, usize).ok())
.map(|(qty, from, to)| Instruction {
qty,
from: from - 1,
to: to - 1,
});
(crates, instructions)
}
}
impl solver::Solver<2022, 5> for Solver {
type Part1 = String;
type Part2 = String;
fn solve_part_one(&self, input: &str) -> Self::Part1 {
let (mut stacks, instructions) = Solver::parse(input);
for ins in instructions {
for _ in 0..ins.qty {
let item = stacks[ins.from].pop_front().unwrap();
stacks[ins.to].push_front(item);
}
}
stacks
.into_iter()
.filter_map(|mut stack| stack.pop_front())
.collect()
}
fn solve_part_two(&self, input: &str) -> Self::Part2 {
let (mut stacks, instructions) = Solver::parse(input);
let mut holding = VecDeque::new();
for ins in instructions {
for _ in 0..ins.qty {
let item = stacks[ins.from].pop_front().unwrap();
holding.push_back(item);
}
for _ in 0..ins.qty {
let item = holding.pop_back().unwrap();
stacks[ins.to].push_front(item);
}
}
stacks
.into_iter()
.filter_map(|mut stack| stack.pop_front())
.collect()
}
}