Skip to main content

aoc/year2019/
day03.rs

1//! # Crossed Wires
2//!
3//! The input follows some implicit rules that can be used to simplify our approach:
4//!
5//! * Wires cross only at right angles to each other, so we only need to consider horizontal lines
6//!   when moving vertically and vice-versa.
7//! * There is only a single vertical line at a given x coordinate and vice-versa.
8//!
9//! This makes [`BTreeMap`] a great choice to store horizontal or vertical line segments as there
10//! are no collisions. The [`range`] method can lookup all line segments contained between two
11//! coordinates to check for intersections.
12//!
13//! First we build two maps, one vertical and one horizontal, of each line segment for the first
14//! wire. Then we trace the steps of the second wire, looking for any intersections. We calculate
15//! both part one and part two at the same time, by also including the distance so far
16//! from the starting point of each line.
17//!
18//! [`range`]: BTreeMap::range
19use std::collections::BTreeMap;
20
21use crate::util::integer::*;
22use crate::util::parse::*;
23use crate::util::point::*;
24
25type Input = (i32, i32);
26
27struct Line {
28    start: Point,
29    end: Point,
30    distance: i32,
31}
32
33pub fn parse(input: &str) -> Input {
34    let (first, second) = input.split_once('\n').unwrap();
35
36    // Build two maps, one for vertical segments and one for horizontal.
37    let mut vertical = BTreeMap::new();
38    let mut horizontal = BTreeMap::new();
39
40    for line in lines(first) {
41        if line.start.x == line.end.x {
42            vertical.insert(line.start.x, line);
43        } else {
44            horizontal.insert(line.start.y, line);
45        }
46    }
47
48    // Trace the steps of the second wire, checking for intersections.
49    let mut manhattan = i32::MAX;
50    let mut delay = i32::MAX;
51
52    for Line { start, end, distance } in lines(second) {
53        // Checks for intersections, ignoring the initial intersection at the origin.
54        let mut update = |line: &Line, candidate: Point| {
55            let length = line.start.manhattan(line.end);
56            if candidate.manhattan(line.start) < length
57                && candidate.manhattan(line.end) < length
58                && candidate != ORIGIN
59            {
60                manhattan = manhattan.min(candidate.manhattan(ORIGIN));
61                delay = delay.min(
62                    distance
63                        + candidate.manhattan(start)
64                        + line.distance
65                        + candidate.manhattan(line.start),
66                );
67            }
68        };
69
70        // BTreeMaps are sorted and can return all key/value pairs in a range.
71        if start.x == end.x {
72            let (lo, hi) = start.y.minmax(end.y);
73            for (&y, line) in horizontal.range(lo..=hi) {
74                update(line, Point::new(start.x, y));
75            }
76        } else {
77            let (lo, hi) = start.x.minmax(end.x);
78            for (&x, line) in vertical.range(lo..=hi) {
79                update(line, Point::new(x, start.y));
80            }
81        }
82    }
83
84    (manhattan, delay)
85}
86
87pub fn part1(input: &Input) -> i32 {
88    input.0
89}
90
91pub fn part2(input: &Input) -> i32 {
92    input.1
93}
94
95/// Map a wire into an iterator of line segments, each with the distance so far to its start.
96fn lines(wire: &str) -> impl Iterator<Item = Line> {
97    let directions = wire.bytes().filter(u8::is_ascii_alphabetic);
98    let amounts = wire.iter_signed();
99    let mut start = ORIGIN;
100    let mut distance = 0;
101
102    directions.zip(amounts).map(move |(direction, amount)| {
103        let line = Line { start, end: start + Point::from(direction) * amount, distance };
104        start = line.end;
105        distance += amount;
106        line
107    })
108}