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
|
/// --- Part Two ---
///
/// As you watch the crane operator expertly rearrange the crates, you notice the process isn't
/// following your prediction.
///
/// Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The
/// crane isn't a CrateMover 9000 - it's a CrateMover 9001.
///
/// The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather
/// seats, an extra cup holder, and the ability to pick up and move multiple crates at once.
///
/// Again considering the example above, the crates begin in the same configuration:
///
/// ```
/// [D]
/// [N] [C]
/// [Z] [M] [P]
/// 1 2 3
/// ```
///
/// Moving a single crate from stack 2 to stack 1 behaves the same as before:
///
/// ```
/// [D]
/// [N] [C]
/// [Z] [M] [P]
/// 1 2 3
/// ```
///
/// However, the action of moving three crates from stack 1 to stack 3 means that those three moved
/// crates stay in the same order, resulting in this new configuration:
///
/// ```
/// [D]
/// [N]
/// [C] [Z]
/// [M] [P]
/// 1 2 3
/// ```
///
/// Next, as both crates are moved from stack 2 to stack 1, they retain their order as well:
///
/// ```
/// [D]
/// [N]
/// [C] [Z]
/// [M] [P]
/// 1 2 3
/// ```
///
/// Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved:
///
/// ```
/// [D]
/// [N]
/// [Z]
/// [M] [C] [P]
/// 1 2 3
/// ```
///
/// In this example, the CrateMover 9001 has put the crates in a totally different order: MCD.
///
/// Before the rearrangement process finishes, update your simulation so that the Elves know where
/// they should stand to be ready to unload the final supplies. 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) {
let popped = (0..order.amount)
.into_iter()
.map(|_| self.pop(order.from))
.collect_vec();
for c in popped.into_iter().rev() {
self.push(order.to, c);
}
}
}
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());
}
|