-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday2.rs
115 lines (98 loc) · 2.42 KB
/
day2.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 aoc_2021::shared::{Day, read_input_lines};
use crate::Move::{Down, Forward, Up};
fn main() {
Day2::new(read_input_lines(2)).run()
}
struct Day2 {
moves: Vec<Move>,
}
enum Move {
Forward(isize),
Up(isize),
Down(isize),
}
struct Position {
horizontal: isize,
depth: isize,
aim: isize,
}
impl Day2 {
fn new(input: Vec<String>) -> Self {
Day2 {
moves: input.iter().map(|s| Day2::parse(s.as_str())).collect()
}
}
fn parse(raw: &str) -> Move {
let split: Vec<&str> = raw.split(' ').collect();
let (direction, unit) = (split[0], split[1].parse::<isize>().unwrap());
match direction {
"forward" => Forward(unit),
"up" => Up(unit),
"down" => Down(unit),
_ => panic!("Unknown direction {}", direction)
}
}
}
impl Position {
fn new() -> Position {
Position { horizontal: 0, depth: 0, aim: 0 }
}
fn shift(&mut self, shift: &Move) {
match shift {
Forward(u) => self.horizontal += u,
Up(u) => self.depth += u,
Down(u) => self.depth -= u
}
}
fn aim(&mut self, aim: &Move) {
match aim {
Forward(u) => {
self.horizontal += u;
self.depth += self.aim * u
}
Up(u) => self.aim -= u,
Down(u) => self.aim += u
}
}
fn result(&self) -> usize {
(self.horizontal * self.depth.abs()) as usize
}
}
impl Day for Day2 {
fn part1(&self) -> usize {
let position = self.moves.iter().fold(Position::new(), |mut acc, cur| {
acc.shift(cur);
acc
});
position.result()
}
fn part2(&self) -> usize {
let position = self.moves.iter().fold(Position::new(), |mut acc, cur| {
acc.aim(cur);
acc
});
position.result()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_sample() {
assert_eq!(sample_day().part1(), 150)
}
#[test]
fn part2_sample() {
assert_eq!(sample_day().part2(), 900)
}
fn sample_day() -> Day2 {
Day2::new(vec![
String::from("forward 5"),
String::from("down 5"),
String::from("forward 8"),
String::from("up 3"),
String::from("down 8"),
String::from("forward 2"),
])
}
}