generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 2
/
02.rs
66 lines (56 loc) · 1.67 KB
/
02.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
type Input = Vec<(u32, u32)>;
fn parse(input: &str) -> Input {
input
.lines()
.filter_map(|l| {
// normalize to index 0 with ASCII table. (A -> 65 | X -> 88)
let bytes = l.as_bytes();
Some(((bytes.first()? - 65) as u32, (bytes.last()? - 88) as u32))
})
.collect()
}
fn score_distance(theirs: u32, ours: u32) -> u32 {
// game result can be determined by calculating wrapped distance.
// use modulo to map indexes (0, 1, 2) to (loss, draw, win) for multiplication with 3.
let score = (3 - (2 + theirs - ours) % 3) % 3 * 3;
score + ours + 1
}
pub fn part_one(input: Input) -> Option<u32> {
Some(
input
.iter()
.map(|&(theirs, ours)| score_distance(theirs, ours))
.sum(),
)
}
pub fn part_two(input: Input) -> Option<u32> {
let score = input
.iter()
.map(|&(theirs, result)| {
// reverse scoring method to find our strategy for round.
let ours = match result {
0 => (theirs + 2) % 3,
1 => theirs,
2 => (theirs + 1) % 3,
_ => unreachable!(),
};
score_distance(theirs, ours)
})
.sum();
Some(score)
}
advent_of_code::main!(2);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(parse(&advent_of_code::template::read_file("examples", 2)));
assert_eq!(result, Some(15));
}
#[test]
fn test_part_two() {
let result = part_two(parse(&advent_of_code::template::read_file("examples", 2)));
assert_eq!(result, Some(12));
}
}