-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday02.rs
More file actions
70 lines (64 loc) · 1.46 KB
/
day02.rs
File metadata and controls
70 lines (64 loc) · 1.46 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
use aoc_runner_derive::{aoc, aoc_generator};
enum Moves {
Forward(i32),
Up(i32),
Down(i32),
}
#[aoc_generator(day2)]
fn parse_input(input: &str) -> Vec<Moves> {
input
.lines()
.map(|l| {
let split: Vec<&str> = l.splitn(2, ' ').collect();
let n = split[1].parse().unwrap();
match split[0] {
"forward" => Moves::Forward(n),
"down" => Moves::Down(n),
"up" => Moves::Up(n),
_ => unreachable!(),
}
})
.collect()
}
#[aoc(day2, part1)]
fn part1(input: &[Moves]) -> i32 {
let (hp, d) = input.iter().fold((0, 0), |(hp, d), m| match m {
Moves::Forward(n) => (hp + n, d),
Moves::Up(n) => (hp, d - n),
Moves::Down(n) => (hp, d + n),
});
hp * d
}
#[aoc(day2, part2)]
fn part2(input: &[Moves]) -> i32 {
let (hp, d, _) = input.iter().fold((0, 0, 0), |(hp, d, a), m| match m {
Moves::Forward(n) => (hp + n, d + a * n, a),
Moves::Up(n) => (hp, d, a - n),
Moves::Down(n) => (hp, d, a + n),
});
hp * d
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample1() {
let input = "forward 5
down 5
forward 8
up 3
down 8
forward 2";
assert_eq!(part1(&parse_input(input)), 150);
}
#[test]
fn sample2() {
let input = "forward 5
down 5
forward 8
up 3
down 8
forward 2";
assert_eq!(part2(&parse_input(input)), 900);
}
}