-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_02.rs
104 lines (86 loc) · 2.12 KB
/
day_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
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
use common::{solution, Answer};
solution!("Rock Paper Scissors", 2);
fn part_a(input: &str) -> Answer {
let mut score = 0;
for (other, self_) in input
.lines()
.filter(|x| !x.is_empty())
.map(|x| x.split_once(' ').unwrap())
{
let other_move = Move::from_str(other);
let self_move = Move::from_str(self_);
score += self_move as u32 + 1;
score += score_round(other_move, self_move).to_score();
}
score.into()
}
fn part_b(input: &str) -> Answer {
let mut score = 0;
for (other, self_) in input
.lines()
.filter(|x| !x.is_empty())
.map(|x| x.split_once(' ').unwrap())
{
let other_move = Move::from_str(other);
let self_move = match self_ {
"X" => other_move.derive(false),
"Y" => other_move,
"Z" => other_move.derive(true),
_ => unreachable!(),
};
score += self_move as u32 + 1;
score += score_round(other_move, self_move).to_score();
}
score.into()
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum Outcome {
Win,
Lose,
Tie,
}
impl Move {
fn from_str(s: &str) -> Self {
match s {
"A" | "X" => Move::Rock,
"B" | "Y" => Move::Paper,
"C" | "Z" => Move::Scissors,
_ => unreachable!(),
}
}
fn from_index(i: usize) -> Self {
match i {
0 => Move::Rock,
1 => Move::Paper,
2 => Move::Scissors,
_ => unreachable!(),
}
}
fn derive(&self, win: bool) -> Self {
Move::from_index((*self as usize + if win { 1 } else { 2 }) % 3)
}
}
impl Outcome {
fn to_score(&self) -> u32 {
match self {
Outcome::Lose => 0,
Outcome::Tie => 3,
Outcome::Win => 6,
}
}
}
fn score_round(other: Move, self_: Move) -> Outcome {
if other == self_ {
return Outcome::Tie;
}
if (other as u32 + 1) % 3 == self_ as u32 {
return Outcome::Win;
}
Outcome::Lose
}