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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
|
use rpds::vector::Vector;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::process;
use std::str::FromStr;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "Day 3: Crossed Wires")]
/// Finds the closest intersection between two wires. By default,
/// 'closest' is defined as closest in terms of Manhattan distance. If
/// --signal-distance is set, distance is defined in terms of the
/// total distance along the wire.
///
/// See https://adventofcode.com/2019/day/3 for details.
struct Opt {
#[structopt(short = "s", long = "signal-distance")]
/// returns the closest intersection by signal distance.
signal_distance: bool,
}
fn main() {
let stdin = io::stdin();
let opt = Opt::from_args();
let mut input = stdin
.lock()
.lines()
.map(|x| exit_on_failed_assertion(x, "Error reading input"))
.map(|x| exit_on_failed_assertion(x.parse::<Wire>(), "Input was not a valid wire"));
let (wire1, wire2) = match (input.next(), input.next()) {
(Some(w1), Some(w2)) => (w1, w2),
_ => {
eprintln!("Input must have two wires");
process::exit(1);
}
};
match wire1.closest_collision(&wire2, opt.signal_distance) {
Some(c) => println!(
"{}",
if opt.signal_distance {
c.signal_distance
} else {
c.manhattan_distance()
}
),
None => {
eprintln!("No collisions");
process::exit(1);
}
}
}
fn exit_on_failed_assertion<A, E: std::error::Error>(data: Result<A, E>, message: &str) -> A {
match data {
Ok(data) => data,
Err(e) => {
eprintln!("{}: {}", message, e);
process::exit(1);
}
}
}
#[derive(Debug, Clone)]
struct Wire {
segments: Vector<WireSegment>,
}
impl FromStr for Wire {
type Err = UnknownError;
fn from_str(s: &str) -> Result<Self, UnknownError> {
s.split(',')
.fold(
Ok(Vector::new()),
|acc: Result<Vector<WireSegment>, UnknownError>, next_str| {
acc.and_then(|previous_segments| {
WireSegment::from_str(
previous_segments.last().map(|l| l.end()).unwrap_or((0, 0)),
previous_segments
.last()
.map(|l| l.end_signal_distance())
.unwrap_or(0),
next_str,
)
.map(|seg| previous_segments.push_back(seg))
})
},
)
.map(|segments| Wire { segments })
}
}
impl Wire {
fn closest_collision(&self, other: &Wire, use_signal_distance: bool) -> Option<Collision> {
self.collisions(other).min_by_key(|c| {
if use_signal_distance {
c.signal_distance
} else {
c.manhattan_distance()
}
})
}
fn collisions<'a>(&'a self, other: &'a Wire) -> impl Iterator<Item = Collision> + 'a {
self.segments
.iter()
.flat_map(move |seg1| other.segments.iter().map(move |seg2| (seg1, seg2)))
.flat_map(|(seg1, seg2)| seg1.collisions(seg2))
.filter(|c| !(c.x == 0 && c.y == 0))
}
}
#[derive(Debug, Clone)]
struct WireSegment {
start: (i32, i32),
start_signal_distance: i32,
direction: Direction,
length: i32,
}
impl WireSegment {
fn from_str(
start: (i32, i32),
start_signal_distance: i32,
s: &str,
) -> Result<Self, UnknownError> {
s.parse::<Direction>().and_then(|direction| {
WireSegment::length_from_str(s).map(|length| WireSegment {
start,
start_signal_distance,
direction,
length,
})
})
}
fn length_from_str(s: &str) -> Result<i32, UnknownError> {
s.chars()
.skip(1)
.collect::<String>()
.parse()
.map_err(|_| UnknownError)
}
fn end(&self) -> (i32, i32) {
(
self.start.0 + self.direction.as_vec().0 * self.length,
self.start.1 + self.direction.as_vec().1 * self.length,
)
}
fn end_signal_distance(&self) -> i32 {
self.start_signal_distance + self.length
}
fn collisions(&self, other: &WireSegment) -> Option<Collision> {
use Direction::*;
match (self.direction, other.direction) {
(Left, Left) | (Right, Right) | (Up, Up) | (Down, Down) => None,
(Left, Right) | (Right, Left) | (Up, Down) | (Down, Up) => None,
(Left, Up) => collisions(
self.end(),
self.end_signal_distance(),
self.length,
-1,
other.start,
other.start_signal_distance,
other.length,
1,
),
(Left, Down) => collisions(
self.end(),
self.end_signal_distance(),
self.length,
-1,
other.end(),
other.end_signal_distance(),
other.length,
-1,
),
(Right, Up) => collisions(
self.start,
self.start_signal_distance,
self.length,
1,
other.start,
other.start_signal_distance,
other.length,
1,
),
(Right, Down) => collisions(
self.start,
self.start_signal_distance,
self.length,
1,
other.end(),
other.end_signal_distance(),
other.length,
-1,
),
(Down, Right) => collisions(
other.start,
other.start_signal_distance,
other.length,
1,
self.end(),
self.end_signal_distance(),
self.length,
-1,
),
(Down, Left) => collisions(
other.end(),
other.end_signal_distance(),
other.length,
-1,
self.end(),
self.end_signal_distance(),
self.length,
-1,
),
(Up, Right) => collisions(
other.start,
other.start_signal_distance,
other.length,
1,
self.start,
self.start_signal_distance,
self.length,
1,
),
(Up, Left) => collisions(
other.end(),
other.end_signal_distance(),
other.length,
-1,
self.start,
self.start_signal_distance,
self.length,
1,
),
}
}
}
fn collisions(
horizontal_start: (i32, i32),
horizontal_start_signal_distance: i32,
horizontal_length: i32,
horizontal_signal_distance_multiplier: i32,
vertical_start: (i32, i32),
vertical_start_signal_distance: i32,
vertical_length: i32,
vertical_signal_distance_multiplier: i32,
) -> Option<Collision> {
if horizontal_start.1 >= vertical_start.1
&& horizontal_start.1 <= vertical_start.1 + vertical_length
&& vertical_start.0 >= horizontal_start.0
&& vertical_start.0 <= horizontal_start.0 + horizontal_length
{
Some(Collision {
x: vertical_start.0,
y: horizontal_start.1,
signal_distance: horizontal_start_signal_distance
+ (vertical_start.0 - horizontal_start.0) * horizontal_signal_distance_multiplier
+ vertical_start_signal_distance
+ (horizontal_start.1 - vertical_start.1) * vertical_signal_distance_multiplier,
})
} else {
None
}
}
#[derive(Debug, Clone, Copy)]
enum Direction {
Up,
Down,
Left,
Right,
}
impl FromStr for Direction {
type Err = UnknownError;
fn from_str(s: &str) -> Result<Self, UnknownError> {
use Direction::*;
match s.chars().next() {
Some('L') => Ok(Left),
Some('R') => Ok(Right),
Some('U') => Ok(Up),
Some('D') => Ok(Down),
Some(_) => Err(UnknownError),
None => Err(UnknownError),
}
}
}
impl Direction {
fn as_vec(&self) -> (i32, i32) {
use Direction::*;
match self {
Up => (0, 1),
Down => (0, -1),
Left => (-1, 0),
Right => (1, 0),
}
}
}
struct Collision {
x: i32,
y: i32,
signal_distance: i32,
}
impl Collision {
fn manhattan_distance(&self) -> i32 {
self.x.abs() + self.y.abs()
}
}
#[derive(Debug, PartialEq)]
struct UnknownError;
impl fmt::Display for UnknownError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Unknown error")
}
}
impl std::error::Error for UnknownError {}
|