-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
225 lines (188 loc) · 5.58 KB
/
main.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
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
#![feature(slice_partition_dedup)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
use std::collections::HashSet;
use util::math::gcd;
enum CellContents {
Empty,
Asteroid,
}
impl CellContents {
fn from_char(c: char) -> Self {
match c {
'.' => CellContents::Empty,
'#' => CellContents::Asteroid,
other => panic!("Unrecognized asteroid map char: {}", other),
}
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
struct Coord {
x: i32,
y: i32,
}
impl std::ops::Sub for Coord {
type Output = Coord;
fn sub(self, other: Coord) -> Self::Output {
Coord {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Coord {
fn new(x: i32, y: i32) -> Self {
Self {
x, y
}
}
/// For a Coord of the form {N*x, N*y}, returns the tuple ({x, y}, N) where N >= 0.
fn simplify(self) -> (Self, i32) {
let n = gcd(self.y, self.x).abs();
if n == 0 {
(Coord {
x: 0,
y: 0,
}, 0)
} else {
(Coord {
x: self.x / n,
y: self.y / n,
}, n)
}
}
/// Clockwise angle in radians from straight up.
fn angle(&self) -> f32 {
// atan2 returns from the range [-pi, +pi] radians from (1, 0)
// Additionally, the y coordinate in the puzzle is backwards, ie, +ve y is down.
let raw = (-self.y as f32).atan2(self.x as f32);
let against_vertical = std::f32::consts::FRAC_PI_2 - raw;
// Normalize the angle to the range [0, 2*pi]
let two_pi = 2f32 * std::f32::consts::PI;
let normalized = (against_vertical + two_pi).rem_euclid(two_pi);
normalized
}
}
struct AsteroidField {
locs: Vec<Coord>,
}
impl AsteroidField {
fn load_from_str(data: &str) -> Self {
let mut locs = Vec::new();
for (y, row_str) in data.lines().enumerate() {
for (x, c) in row_str.chars().enumerate() {
match CellContents::from_char(c) {
CellContents::Empty => (),
CellContents::Asteroid => locs.push(Coord::new(x as i32, y as i32)),
}
}
}
Self {
locs: locs,
}
}
fn load_from_file(path: &Path) -> Self {
let mut file = File::open(path)
.expect("Failed to open asteroid field file");
let mut data = String::new();
file.read_to_string(&mut data)
.expect("Failed to read asteroid field file");
Self::load_from_str(&data)
}
}
fn main() {
let field = AsteroidField::load_from_file(Path::new("./input.txt"));
let mut best: Option<(Coord, usize)> = None;
for root in field.locs.iter() {
let score = field.locs
.iter()
.filter(|other| *other != root)
.map(|other| {
let (base, _n) = (*other - *root).simplify();
base
})
.collect::<HashSet<_>>()
.len();
match best {
Some((_, curr_best_score)) if curr_best_score > score => (),
_ => best = Some((*root, score)),
}
}
dbg!(&best);
let station_loc = best.unwrap().0;
let mut targets = field.locs
.iter()
.filter(|target| **target != station_loc)
.map(|target| {
let (base, n) = (*target - station_loc).simplify();
(target, base, n)
})
.collect::<Vec<_>>();
targets.sort_by_key(|(_, _, n)| *n);
targets.sort_by(|(_, a, _), (_, b, _)| a.angle().partial_cmp(&b.angle()).unwrap());
loop {
let (uniques, duplicates) = targets.partition_dedup_by_key(|(_, a, _)| *a);
if duplicates.len() == 0 ||
duplicates.iter().all(|(_, base, _)| *base == uniques.last().unwrap().1)
{
break;
}
}
assert!(targets.len() >= 200);
dbg!(&targets[199]);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_coord_simplify_positive() {
let c = Coord::new(4, 6);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(2, 3));
assert_eq!(n, 2);
}
#[test]
fn test_coord_simplify_negative() {
let c = Coord::new(-10, -20);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(-1, -2));
assert_eq!(n, 10);
}
#[test]
fn test_coord_simplify_mixed_1() {
let c = Coord::new(5, -15);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(1, -3));
assert_eq!(n, 5);
}
#[test]
fn test_coord_simplify_mixed_2() {
let c = Coord::new(-5, 15);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(-1, 3));
assert_eq!(n, 5);
}
#[test]
fn test_coord_simplify_zero_x() {
let c = Coord::new(0, 5);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(0, 1));
assert_eq!(n, 5);
let c = Coord::new(0, -5);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(0, -1));
assert_eq!(n, 5);
}
#[test]
fn test_coord_simplify_zero_y() {
let c = Coord::new(5, 0);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(1, 0));
assert_eq!(n, 5);
let c = Coord::new(-5, 0);
let (simplified, n) = c.simplify();
assert_eq!(simplified, Coord::new(-1, 0));
assert_eq!(n, 5);
}
}