-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.rs
77 lines (61 loc) · 1.56 KB
/
day3.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
//! [Day 3: Toboggan Trajectory](https://adventofcode.com/2020/day/3)
use aoc::grid;
type Grid = aoc::grid::Grid<u8>;
struct Puzzle {
grid: Grid,
}
impl Puzzle {
fn new() -> Puzzle {
Puzzle { grid: grid!() }
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
self.grid = Grid::parse(&data);
}
fn trees(&self, slope_x: usize, slope_y: usize) -> u64 {
let mut x = 0;
let mut y = 0;
let mut n = 0;
while y < self.grid.size().1 {
if self.grid[(x, y)] == b'#' {
n += 1;
}
x = (x + slope_x) % self.grid.size().0;
y += slope_y;
}
n
}
/// Solve part one.
fn part1(&self) -> u64 {
self.trees(3, 1)
}
/// Solve part two.
fn part2(&self) -> u64 {
self.trees(1, 1) * self.trees(3, 1) * self.trees(5, 1) * self.trees(7, 1) * self.trees(1, 2)
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 7);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 336);
}
}