generated from sindrekjr/AdventOfCodeBase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
d08.rs
115 lines (94 loc) · 3.4 KB
/
d08.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
use std::collections::HashSet;
use crate::core::{Part, Solution};
pub fn solve(part: Part, input: String) -> String {
match part {
Part::P1 => Day08::solve_part_one(input),
Part::P2 => Day08::solve_part_two(input),
}
}
struct Day08;
impl Solution for Day08 {
fn solve_part_one(input: String) -> String {
let lines: Vec<&str> = input.lines().collect();
let h = lines.len() as isize;
let w = lines[0].len() as isize;
let nodes: HashSet<(char, usize, usize)> = lines
.iter()
.enumerate()
.flat_map(|(y, line)| {
line.char_indices().filter_map(move |(x, ch)| match ch {
'.' => None,
ch => Some((ch, x, y)),
})
})
.collect();
let antinodes: HashSet<(usize, usize)> = nodes
.iter()
.flat_map(|&(ch, x, y)| {
let mut antinodes = vec![];
for &(i_ch, i_x, i_y) in &nodes {
if i_ch != ch {
continue;
}
if i_x == x && i_y == y {
continue;
}
let diff_x = x as isize - i_x as isize;
let diff_y = y as isize - i_y as isize;
let new_x = x as isize + diff_x;
let new_y = y as isize + diff_y;
if new_x >= 0 && new_x < w && new_y >= 0 && new_y < h {
antinodes.push((new_x as usize, new_y as usize));
}
}
antinodes
})
.collect();
antinodes.len().to_string()
}
fn solve_part_two(input: String) -> String {
let lines: Vec<&str> = input.lines().collect();
let h = lines.len() as isize;
let w = lines[0].len() as isize;
let nodes: HashSet<(char, usize, usize)> = lines
.iter()
.enumerate()
.flat_map(|(y, line)| {
line.char_indices().filter_map(move |(x, ch)| match ch {
'.' => None,
ch => Some((ch, x, y)),
})
})
.collect();
let antinodes: HashSet<(usize, usize)> = nodes
.iter()
.flat_map(|&(ch, x, y)| {
let mut antinodes = vec![];
for &(i_ch, i_x, i_y) in &nodes {
if i_ch != ch {
continue;
}
if i_x == x && i_y == y {
antinodes.push((x, y));
continue;
}
let diff_x = x as isize - i_x as isize;
let diff_y = y as isize - i_y as isize;
let mut i = 1;
loop {
let new_x = x as isize + (diff_x * i);
let new_y = y as isize + (diff_y * i);
if new_x >= 0 && new_x < w && new_y >= 0 && new_y < h {
antinodes.push((new_x as usize, new_y as usize));
i += 1;
} else {
break;
}
}
}
antinodes
})
.collect();
antinodes.len().to_string()
}
}