1use 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 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 let mut manhattan = i32::MAX;
50 let mut delay = i32::MAX;
51
52 for Line { start, end, distance } in lines(second) {
53 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 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
95fn 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}