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
|
use std::cmp::{max, min};
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let reader = open_file();
let mut coords: HashMap<(i32, i32), i32> = HashMap::new();
for line in reader.lines() {
if let Ok(line) = line {
let vents = line.split(" -> ").collect::<Vec<&str>>();
let first = vents[0].split(",").collect::<Vec<&str>>();
let second = vents[1].split(",").collect::<Vec<&str>>();
let first: Vec<i32> = first.into_iter().map(|s| s.parse().unwrap()).collect();
let second: Vec<i32> = second.into_iter().map(|s| s.parse().unwrap()).collect();
let xstep: i32;
let ystep: i32;
let start_x = min(first[0], second[0]);
let end_x = max(first[0], second[0]);
let start_y = min(first[1], second[1]);
let end_y = max(first[1], second[1]);
let distance = max(end_x - start_x, end_y - start_y);
if first[0] > second[0] {
xstep = -1;
} else if first[0] < second[0] {
xstep = 1;
} else {
xstep = 0;
}
if first[1] > second[1] {
ystep = -1;
} else if first[1] < second[1] {
ystep = 1;
} else {
ystep = 0;
}
for step in 0..=distance {
let counter = coords
.entry((first[0] + step * xstep, first[1] + step * ystep))
.or_insert(0);
*counter += 1;
}
}
}
// println!("coords: {:?}", coords);
// visualize(&coords);
let result = coords.iter().filter(|(_, &y)| y >= 2).count();
println!("{}", result);
}
fn visualize(map: &HashMap<(i32, i32), i32>) {
let start_x = map.iter().map(|((x, _), _)| x).min().unwrap();
let start_y = map.iter().map(|((_, y), _)| y).min().unwrap();
let end_x = map.iter().map(|((x, _), _)| x).max().unwrap();
let end_y = map.iter().map(|((_, y), _)| y).max().unwrap();
println!("start_x: {}", start_x);
println!("start_y: {}", start_y);
println!("end_x: {}", end_x);
println!("end_y: {}", end_y);
for y in *start_y..=*end_y {
for x in *start_x..=*end_x {
if let Some(val) = map.get(&(x, y)) {
print!("{}", val);
} else {
print!(".")
}
}
println!("");
}
}
fn open_file() -> BufReader<File> {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: {} <filename>", args[0]);
std::process::exit(1);
}
let filename = &args[1];
let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename));
BufReader::new(file)
}
|