-
Notifications
You must be signed in to change notification settings - Fork 0
/
05.rs
68 lines (62 loc) · 1.75 KB
/
05.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
#![feature(test)]
type Input = (Vec<String>, Vec<(usize, usize, usize)>);
pub fn solve((stacks, instructions): &Input, get_next: fn(usize, usize) -> usize) -> String {
(0..stacks.len())
.map(|mut st| {
let mut h = 0;
for &(cnt, i, j) in instructions.iter().rev() {
if st == j {
if h < cnt {
st = i;
h = (get_next)(cnt, h);
} else {
h -= cnt;
}
} else if st == i {
h += cnt;
}
}
stacks[st].chars().nth_back(h).unwrap()
})
.collect()
}
fn setup(input: &str) -> Input {
let (initial, instructions) = input.split_once("\n\n").unwrap();
let mut it = initial.lines().rev();
let mut stacks: Vec<_> = it
.next()
.unwrap()
.split_whitespace()
.map(|_| String::new())
.collect();
for line in it {
for (i, c) in line
.chars()
.skip(1)
.step_by(4)
.enumerate()
.filter(|(_, x)| *x != ' ')
{
stacks[i].push(c);
}
}
let instructions = instructions
.lines()
.map(|line| {
let mut it = line
.split_whitespace()
.skip(1)
.step_by(2)
.map(|x| x.parse().unwrap());
(|| Some((it.next()?, it.next()? - 1, it.next()? - 1)))().unwrap()
})
.collect();
(stacks, instructions)
}
fn part1(input: &Input) -> String {
solve(input, |cnt, h| cnt - h - 1)
}
fn part2(input: &Input) -> String {
solve(input, |_, h| h)
}
aoc::main!(2022, 5, ex: 1);