generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
08.rs
81 lines (62 loc) · 1.94 KB
/
08.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
use std::collections::HashSet;
use advent_of_code::{ascii_map_size, parse_ascii_map_ivec};
use itertools::Itertools;
advent_of_code::solution!();
pub fn part_one(input: &str) -> Option<u32> {
let map_size = ascii_map_size(input);
let antennas = parse_ascii_map_ivec(input);
let antennas_couples = antennas
.tuple_combinations()
.filter(|((_, freq_a), (_, freq_b))| freq_a == freq_b)
.map(|((a, _), (b, _))| (a, b));
let anti_nodes = antennas_couples
.flat_map(|(a, b)| [2 * b - a, 2 * a - b])
.filter(|&pos| map_size.contains(pos))
.collect::<HashSet<_>>();
Some(anti_nodes.len().try_into().unwrap())
}
pub fn part_two(input: &str) -> Option<u32> {
let map_size = ascii_map_size(input);
let antennas = parse_ascii_map_ivec(input);
let antennas_couples = antennas
.tuple_combinations()
.filter(|((_, freq_a), (_, freq_b))| freq_a == freq_b)
.map(|((a, _), (b, _))| (a, b));
let mut anti_nodes = HashSet::new();
for (a, b) in antennas_couples {
let v = a - b;
anti_nodes.insert(a);
anti_nodes.insert(b);
for n in 0.. {
let u = a + v * n;
if map_size.contains(u) {
anti_nodes.insert(u);
} else {
break;
}
}
for n in 0.. {
let u = b - v * n;
if map_size.contains(u) {
anti_nodes.insert(u);
} else {
break;
}
}
}
Some(anti_nodes.len().try_into().unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(14));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(34));
}
}