Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epidemian
GitHub Repository: epidemian/advent-of-code-2021
Path: blob/main/src/day05.rs
97 views
1
use std::collections::HashMap;
2
3
pub fn run() {
4
let all_lines: Vec<Line> = include_str!("inputs/day05")
5
.lines()
6
.map(parse_line)
7
.collect();
8
let non_diagonal_lines: Vec<Line> = all_lines
9
.iter()
10
.filter(|(x1, y1, x2, y2)| x1 == x2 || y1 == y2)
11
.map(|l| l.clone())
12
.collect();
13
14
println!("{}", count_overlaps(&non_diagonal_lines));
15
println!("{}", count_overlaps(&all_lines));
16
}
17
18
fn count_overlaps(lines: &[Line]) -> usize {
19
let mut counts = HashMap::new();
20
for &(x1, y1, x2, y2) in lines {
21
let dx = (x2 - x1).signum();
22
let dy = (y2 - y1).signum();
23
let mut x = x1;
24
let mut y = y1;
25
*counts.entry((x, y)).or_insert(0) += 1;
26
while !(x == x2 && y == y2) {
27
x += dx;
28
y += dy;
29
*counts.entry((x, y)).or_insert(0) += 1
30
}
31
}
32
counts.values().filter(|count| **count >= 2).count()
33
}
34
35
type Line = (i32, i32, i32, i32);
36
37
fn parse_line(s: &str) -> Line {
38
let points: Vec<i32> = s
39
.split(" -> ")
40
.flat_map(|p| p.split(","))
41
.map(|s| s.parse().unwrap())
42
.collect();
43
(points[0], points[1], points[2], points[3])
44
}
45
46