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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
/// --- Day 5: Supply Stacks ---
///
/// The expedition can depart as soon as the final supplies have been unloaded from the
/// ships. Supplies are stored in stacks of marked crates, but because the needed supplies are
/// buried under many other crates, the crates need to be rearranged.
///
/// The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of
/// the crates get crushed or fall over, the crane operator will rearrange them in a series of
/// carefully-planned steps. After the crates are rearranged, the desired crates will be at the
/// top of each stack.
///
/// The Elves don't want to interrupt the crane operator during this delicate procedure, but they
/// forgot to ask her which crate will end up where, and they want to be ready to unload them as
/// soon as possible so they can embark.
///
/// They do, however, have a drawing of the starting stacks of crates and the rearrangement
/// procedure (your puzzle input). For example:
///
/// [D]
/// [N] [C]
/// [Z] [M] [P]
/// 1 2 3
///
/// move 1 from 2 to 1
/// move 3 from 1 to 3
/// move 2 from 2 to 1
/// move 1 from 1 to 2
///
/// In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on
/// the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are
/// crates M, C, and D. Finally, stack 3 contains a single crate, P.
///
/// Then, the rearrangement procedure is given. In each step of the procedure, a quantity of
/// crates is moved from one stack to a different stack. In the first step of the above
/// rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this
/// configuration:
///
/// [D]
/// [N] [C]
/// [Z] [M] [P]
/// 1 2 3
///
/// In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a
/// time, so the first crate to be moved (D) ends up below the second and third crates:
///
/// [Z]
/// [N]
/// [C] [D]
/// [M] [P]
/// 1 2 3
///
/// Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a
/// time, crate C ends up below crate M:
///
/// [Z]
/// [N]
/// [M] [D]
/// [C] [P]
/// 1 2 3
///
/// Finally, one crate is moved from stack 1 to stack 2:
///
/// [Z]
/// [N]
/// [D]
/// [C] [M] [P]
/// 1 2 3
///
/// The Elves just need to know which crate will end up on top of each stack; in this example, the
/// top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these
/// together and give the Elves the message CMZ.
///
/// After the rearrangement procedure completes, what crate ends up on top of each stack?
use clap::Parser;
use itertools::Itertools;
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::{alpha1, digit1, multispace1};
use nom::combinator::{map, opt, peek};
use nom::error::{ErrorKind as NomErrorKind, ParseError};
use nom::multi::{many1, many1_count};
use nom::sequence::{delimited, preceded, terminated};
use nom::IResult;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::iter::*;
use std::path::PathBuf;
pub type Input<'a> = &'a str;
pub type Result<'a, T> = IResult<Input<'a>, T, Error<Input<'a>>>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Nom(NomErrorKind),
Context(&'static str),
Custom(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error<I> {
pub errors: Vec<(I, ErrorKind)>,
}
impl<I> ParseError<I> for Error<I> {
fn from_error_kind(input: I, kind: NomErrorKind) -> Self {
let errors = vec![(input, ErrorKind::Nom(kind))];
Self { errors }
}
fn append(input: I, kind: NomErrorKind, mut other: Self) -> Self {
other.errors.push((input, ErrorKind::Nom(kind)));
other
}
}
const FILEPATH: &'static str = "examples/input.txt";
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Cli {
#[clap(short, long, default_value = FILEPATH)]
file: PathBuf,
}
#[derive(Debug, Clone)]
struct Supplies(Vec<Vec<char>>);
#[derive(Debug, Clone)]
struct Order {
from: usize,
to: usize,
amount: usize,
}
#[derive(Debug, Clone)]
enum LineKind {
Axis(usize),
Crates(Vec<char>),
}
fn parse_digit(input: &str) -> Result<char> {
map(preceded(multispace1, digit1), |s: &str| {
s.chars().next().unwrap()
})(input)
}
fn parse_crate(input: &str) -> Result<char> {
map(delimited(tag("["), alpha1, tag("]")), |s: &str| {
s.chars().next().unwrap()
})(input)
}
fn parse_crate_or_empty(input: &str) -> Result<char> {
terminated(alt((map(tag(" "), |_| ' '), parse_crate)), opt(tag(" ")))(input)
}
fn parse_line(input: &str) -> Result<LineKind> {
let res = peek(parse_digit)(input);
if res.is_ok() {
map(many1_count(parse_digit), |len| LineKind::Axis(len))(input)
} else {
map(many1(parse_crate_or_empty), |v| LineKind::Crates(v))(input)
}
}
impl Supplies {
fn new() -> Self {
Self(Vec::<Vec<char>>::new())
}
fn idx_to_internal(idx: usize) -> usize {
idx - 1
}
fn initialize(&mut self, input: Vec<LineKind>) {
let axis = &input[input.len() - 1];
let LineKind::Axis(len) = axis else {
panic!();
};
self.resize(*len);
let _ = input
.into_iter()
.rev()
.skip(1)
.map(|x| match x {
LineKind::Crates(v) => v,
_ => panic!(),
})
.map(|vc| {
vc.into_iter()
.zip(1usize..)
.filter(|(c, _)| *c != ' ')
.collect_vec()
})
.flatten()
.scan(self, |state, (c, idx)| {
state.push(idx, c);
Some(())
})
.last();
}
fn pop(&mut self, idx: usize) -> char {
self.0[Self::idx_to_internal(idx)].pop().unwrap()
}
fn peek(&self, idx: usize) -> char {
self.0[Self::idx_to_internal(idx)][self.0[Self::idx_to_internal(idx)].len() - 1]
}
fn push(&mut self, idx: usize, letter: char) {
self.0[Self::idx_to_internal(idx)].push(letter)
}
fn resize(&mut self, len: usize) {
self.0.resize(len, Vec::<char>::new())
}
fn top_chars(&self) -> String {
(0..self.0.len())
.map(|idx| self.peek(idx + 1).to_string())
.join("")
}
fn transfer(&mut self, order: Order) {
for _ in 0..order.amount {
let v = self.pop(order.from);
self.push(order.to, v);
}
}
}
fn main() {
let args = Cli::parse();
let file = File::open(&args.file).unwrap();
let reader = BufReader::new(file);
let init = reader
.lines()
.map(|l| l.unwrap())
.take_while(|l| !l.is_empty())
.map(|l| parse_line(l.as_str()).unwrap().1)
.collect_vec();
let mut supplies = Supplies::new();
supplies.initialize(init);
let file = File::open(&args.file).unwrap();
let reader = BufReader::new(file);
let _ = reader
.lines()
.map(|l| l.unwrap())
.skip_while(|l| !l.contains("move"))
.map(|l| {
let sp = l.split_whitespace().collect_vec();
Order {
from: sp[3].parse::<usize>().unwrap(),
to: sp[5].parse::<usize>().unwrap(),
amount: sp[1].parse::<usize>().unwrap(),
}
})
.scan(&mut supplies, |state, order| {
state.transfer(order);
Some(())
})
.last();
println!("{}", supplies.top_chars());
}
|