-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday03.rs
More file actions
76 lines (66 loc) · 1.75 KB
/
day03.rs
File metadata and controls
76 lines (66 loc) · 1.75 KB
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
use std::fs;
use std::str::FromStr;
struct Map {
trees: Vec<(usize, usize)>,
width: usize,
height: usize,
}
impl FromStr for Map {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut width = 0;
let mut height = 0;
let mut trees = vec![];
for (i, line) in s.lines().enumerate() {
for (j, c) in line.trim().chars().enumerate() {
if c == '#' {
trees.push((j, i));
} else if c != '.' {
return Err(format!("unknown symbol '{}'", c));
}
width = j;
}
height = i;
}
Ok(Map {
trees,
width,
height,
})
}
}
fn count_trees_on_slope(map: &Map, slope: (usize, usize)) -> usize {
let mut count = 0;
let mut xpos = 0;
let mut ypos = 0;
let (xdir, ydir) = slope;
while ypos <= map.height {
if map.trees.contains(&(xpos, ypos)) {
count += 1;
}
xpos = (xpos + xdir) % (map.width + 1);
ypos += ydir;
}
count
}
fn evaluate_slopes(map: &Map, slopes: Vec<(usize, usize)>) -> usize {
slopes
.into_iter()
.map(|s| count_trees_on_slope(map, s))
.product()
}
fn main() {
let raw_map = fs::read_to_string("./input/day03.txt").expect("File not found!");
let map = match Map::from_str(&raw_map) {
Err(e) => {
eprintln!("Error on parsing map: {}", e);
std::process::exit(-1);
}
Ok(m) => m,
};
println!("p1: {}", count_trees_on_slope(&map, (3, 1)));
println!(
"p2: {}",
evaluate_slopes(&map, vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)])
);
}