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 std::collections::{HashMap, HashSet};
static DAY: u8 = 8;
fn main() {
let input = advent::read_lines(DAY);
println!("{DAY}a: {}", Map::new(&input).count_antinodes(false));
println!("{DAY}b: {}", Map::new(&input).count_antinodes(true));
}
#[derive(Eq, PartialEq, Hash, Clone, Copy)]
struct Position {
x: isize,
y: isize,
}
impl Position {
fn add_position(&self, other: &Position) -> Position {
Position { x: self.x + (self.x - other.x), y: self.y + (self.y - other.y) }
}
}
struct Map {
antennas: HashMap<Position, char>,
dimensions: Position,
}
impl Map {
fn new(input: &[String]) -> Map {
let mut antennas = HashMap::new();
for (y, line) in input.iter().enumerate() {
for (x, c) in line.chars().enumerate() {
if c != '.' {
let pos = Position { x: x as isize, y: y as isize };
antennas.insert(pos, c);
}
}
}
let dimensions = Position { x: input[0].len() as isize, y: input.len() as isize };
Map { antennas, dimensions }
}
fn inside_map(&self, pos: &Position) -> bool {
pos.x >= 0 && pos.y >= 0 && pos.x < self.dimensions.x && pos.y < self.dimensions.y
}
fn get_harmonics(&self, pos1: Position, pos2: Position, with_harmonics: bool) -> HashSet<Position> {
let mut harmonics = HashSet::new();
if with_harmonics {
harmonics.insert(pos1);
harmonics.insert(pos2);
}
let mut prev = pos1;
let mut harmonic = pos2;
loop {
(prev, harmonic) = (harmonic, harmonic.add_position(&prev));
if !self.inside_map(&harmonic) {
break;
}
harmonics.insert(harmonic);
if !with_harmonics {
// only interested in first harmonic
break;
}
}
harmonics
}
fn count_antinodes(&self, with_harmonics: bool) -> usize {
let mut antinodes = HashSet::new();
for (pos1, antenna) in &self.antennas {
for (pos2, _) in self.antennas.iter().filter(|&(_, a)| a == antenna).filter(|&(p, _)| p != pos1) {
let harmonics = self.get_harmonics(*pos1, *pos2, with_harmonics);
for antinode in harmonics {
antinodes.insert(antinode);
}
}
}
antinodes.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let input = [
"............",
"........0...",
".....0......",
".......0....",
"....0.......",
"......A.....",
"............",
"............",
"........A...",
".........A..",
"............",
"............",
].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
assert_eq!(Map::new(&input).count_antinodes(false), 14);
assert_eq!(Map::new(&input).count_antinodes(true), 34);
}
}
|