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
// Adaption of https://github.com/SLiV9/AdventOfCode2022/blob/main/src/bin/day15/main.rs
use crate::input::Input;

const MAX_COORDINATE: i32 = 4_000_000;

pub fn solve(input: &Input) -> Result<u64, String> {
    let sensors = Sensor::parse(input.text).ok_or_else(|| "Invalid input".to_string())?;

    if input.is_part_one() {
        Ok(solve_part_1(&sensors))
    } else {
        solve_part_2(&sensors)
    }
}

type Point = (i32, i32);

#[derive(Copy, Clone)]
struct Sensor {
    position: Point,
    closest_beacon: Point,
    range: u32,
}

impl Sensor {
    fn parse(input: &str) -> Option<Vec<Self>> {
        fn parse_x_y(input: &str) -> Option<Point> {
            let mut parts = input.split(", y=");
            Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
        }

        input
            .lines()
            .map(|line| {
                if line.len() < 20 {
                    return None;
                }
                let mut parts = line[12..].split(": closest beacon is at x=");
                let position = parse_x_y(parts.next()?)?;
                let closest_beacon = parse_x_y(parts.next()?)?;
                let range =
                    position.0.abs_diff(closest_beacon.0) + position.1.abs_diff(closest_beacon.1);
                Some(Self {
                    position,
                    closest_beacon,
                    range,
                })
            })
            .collect()
    }

    const fn contains(&self, position: Point) -> bool {
        self.position.0.abs_diff(position.0) + self.position.1.abs_diff(position.1) <= self.range
    }
}

fn solve_part_1(sensors: &[Sensor]) -> u64 {
    let mut not_possible_intervals = sensors
        .iter()
        .filter_map(|sensor| {
            const ROW: i32 = 2_000_000;

            // Consider the sensor at S:
            //
            //     .........
            //     ....#....
            // R-> ...###...
            //     ..##S##..
            //     ...###...
            //     ....#....
            //     .........
            //
            // The intersection at row R is at:
            //   x_start = S_x - radius + abs(R_y - S_y)
            //   x_end   = S_x + radius - abs(R_y - S_y)
            if ROW.abs_diff(sensor.position.1) <= sensor.range {
                let intersection_distance = ROW.abs_diff(sensor.position.1) as i32;
                let x_start = sensor.position.0 - sensor.range as i32 + intersection_distance;
                let x_end = sensor.position.0 + sensor.range as i32 - intersection_distance;
                // We then need to adjust the intersection if the beacon is there:
                //   R-> ...B#B...
                // That is done by adding one to x_start, or subtracting one from x_end, if necessary.
                Some((
                    x_start + i32::from((x_start, ROW) == sensor.closest_beacon),
                    x_end - i32::from((x_end, ROW) == sensor.closest_beacon),
                ))
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    let mut not_possible_positions_count = 0;
    let mut last_interval = (i32::MIN + 1, i32::MIN);

    not_possible_intervals.sort_unstable_by(|a, b| a.0.cmp(&b.0));

    for interval in not_possible_intervals {
        if interval.0 <= last_interval.1 && interval.1 >= last_interval.0 {
            last_interval = (
                interval.0.min(last_interval.0),
                interval.1.max(last_interval.1),
            );
        } else {
            not_possible_positions_count += last_interval.1 - last_interval.0 + 1;
            last_interval = interval;
        }
    }
    not_possible_positions_count += last_interval.1 - last_interval.0 + 1;

    not_possible_positions_count as u64
}

/// Since there is only one possible space, it (unless it's at the
/// edge of the boundary) needs to be where diagonal lines along the
/// outer edges of the diamond shaped sensor covered areas:
///
/// ..\......./...
/// ...\..#../....
/// ....\#S#/#....
/// ....#\#/####..
/// ...#S#.##S###.
/// ....#/#\###...
/// ..../###\#....
/// .../##S##\....
/// ../.......\...
///
/// These two diagonal lines must come from two different sensors.
///
/// The possible space could also be along the edge of the boundary.
fn solve_part_2(sensors: &[Sensor]) -> Result<u64, String> {
    let ascending_lines = diagonal_line_candidates(sensors, true);
    let descending_lines = diagonal_line_candidates(sensors, false);

    for &ascending_line in ascending_lines.iter() {
        for &descending_line in descending_lines.iter() {
            let intersection = intersection_of(ascending_line, descending_line);
            if is_within_bounds(intersection)
                && !sensors.iter().any(|sensor| sensor.contains(intersection))
            {
                return Ok((intersection.0 as u64) * 4_000_000 + (intersection.1 as u64));
            }
        }
    }

    // Also check the edge of the boundary:
    for offset in 0..=MAX_COORDINATE {
        for position in [
            (0, offset),
            (MAX_COORDINATE, offset),
            (offset, 0),
            (offset, MAX_COORDINATE),
        ] {
            if !sensors.iter().any(|sensor| sensor.contains(position)) {
                return Ok((position.0 as u64) * 4_000_000 + (position.1 as u64));
            }
        }
    }

    Err("No solution found".to_string())
}

/// Returns diagonal lines along the outer edge of sensors, represented as an i32
/// for the x origin. Only duplicated lines are returned, as they are the only
/// candidates for intersections at the only possible space.
fn diagonal_line_candidates(sensors: &[Sensor], ascending: bool) -> Vec<i32> {
    let y_multiplier = if ascending { -1 } else { 1 };

    let mut diagonal_lines = sensors
        .iter()
        .flat_map(|sensor| {
            let outer_edge_leftmost = sensor.position.0 - sensor.range as i32 - 1;
            let outer_edge_rightmost = sensor.position.0 + sensor.range as i32 + 1;
            // Contains the x origins of diagonal (either ascending or descending) lines:
            // .................
            // .........#.......
            // .......x#S#x.....
            // ....../.\#/.\....
            // ...../...X...\...
            // ..../.../.\...\..
            // ---a---a---d---d-
            [
                outer_edge_leftmost + y_multiplier * sensor.position.1,
                outer_edge_rightmost + y_multiplier * sensor.position.1,
            ]
        })
        .collect::<Vec<_>>();

    diagonal_lines.sort_unstable();
    let mut diagonal_lines = diagonal_lines
        .windows(2)
        .filter_map(|window| (window[0] == window[1]).then_some(window[0]))
        .collect::<Vec<_>>();
    diagonal_lines.dedup();
    diagonal_lines
}

const fn is_within_bounds(position: Point) -> bool {
    position.0 >= 0
        && position.0 <= MAX_COORDINATE
        && position.1 >= 0
        && position.1 <= MAX_COORDINATE
}

/// Given the x origin of an ascending (represented with 'a' below) and
/// a descending (represented with 'd' below) line, return the point of
/// intersection (represented with 'x' below):
///
/// ...............
/// .......x.......
/// ....../.\......
/// ...../...\.....
/// ..../.....\....
/// ---a---h---d---
const fn intersection_of(ascending_origin_x: i32, descending_origin_x: i32) -> Point {
    let halfway = (descending_origin_x - ascending_origin_x) / 2;
    (ascending_origin_x + halfway, halfway)
}

#[test]
pub fn tests() {
    use crate::input::{test_part_one, test_part_two};

    let real_input = include_str!("day15_input.txt");
    test_part_one!(real_input => 5_240_818);
    test_part_two!(real_input => 13_213_086_906_101);
}