-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday_15.rs
111 lines (90 loc) · 2.86 KB
/
day_15.rs
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
use common::{solution, Answer};
use nd_vec::vector;
use rayon::prelude::*;
solution!("Beacon Exclusion Zone", 15);
type Point = nd_vec::Vec2<isize>;
fn part_a(input: &str) -> Answer {
let world = World::parse(input);
let y_level = 2000000; // 10 for example
let blocked = (world.bounds.0.x()..=world.bounds.1.x())
.into_par_iter()
.map(|x| vector!(x, y_level))
.filter(|x| world.is_sensed(*x))
.count();
(blocked - 1).into()
}
fn part_b(input: &str) -> Answer {
let world = World::parse(input);
let bounds = 4000000;
let distress = world.search(bounds).expect("No distress beacon found");
(distress.x() * 4000000 + distress.y()).into()
}
struct World {
sensors: Vec<Sensor>,
bounds: (Point, Point),
}
#[derive(Debug)]
struct Sensor {
pos: Point,
distance: isize,
}
impl World {
fn parse(raw: &str) -> Self {
let mut sensors = Vec::new();
let (mut min_bound, mut max_bound) = (Point::default(), Point::default());
for i in raw.lines() {
let sensor = Sensor::parse(i);
min_bound = min_bound.min(&(sensor.pos - sensor.distance));
max_bound = max_bound.max(&(sensor.pos + sensor.distance));
sensors.push(sensor);
}
Self {
sensors,
bounds: (min_bound, max_bound),
}
}
fn search(&self, bounds: isize) -> Option<Point> {
(0..=bounds).into_par_iter().find_map_any(|y| {
for s in &self.sensors {
let x1 = s.pos.x() - (s.distance - (s.pos.y() - y).abs()) - 1;
let x2 = s.pos.x() + (s.distance - (s.pos.y() - y).abs()) + 1;
if x1 > 0 && x1 < bounds && !self.is_sensed(vector!(x1, y)) {
return Some(vector!(x1, y));
}
if x2 > 0 && x2 < bounds && !self.is_sensed(vector!(x2, y)) {
return Some(vector!(x2, y));
}
}
None
})
}
fn is_sensed(&self, point: Point) -> bool {
self.sensors
.iter()
.any(|x| x.pos.manhattan_distance(&point) <= x.distance)
}
}
impl Sensor {
fn parse(raw: &str) -> Self {
let parts = raw.split("at ").collect::<Vec<_>>();
let parse_pos = |pos: &str| {
let parts = pos.split(", ").collect::<Vec<_>>();
vector!(
parts[0].trim_start_matches("x=").parse().unwrap(),
parts[1]
.trim_start_matches("y=")
.split(':')
.next()
.unwrap()
.parse()
.unwrap()
)
};
let pos = parse_pos(parts[1]);
let beacon = parse_pos(parts[2]);
Self {
pos,
distance: pos.manhattan_distance(&beacon),
}
}
}