-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.rs
134 lines (122 loc) · 2.95 KB
/
day02.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use std::str::FromStr;
struct Match {
us: Choice,
them: Choice,
}
impl Match {
pub fn won(&self) -> bool {
self.us.wins_against() == self.them
}
pub fn tied(&self) -> bool {
self.us == self.them
}
pub fn get_score(self) -> i32 {
let match_score = if self.won() {
6
} else if self.tied() {
3
} else {
0
};
match_score + self.us as i32
}
pub fn from_instructions(s: &str) -> Self {
let instructions: Vec<&str> = s.split_whitespace().collect();
let them = Choice::from_str(instructions[0]).unwrap();
let outcome = Outcome::from_str(instructions[1]).unwrap();
let us = match outcome {
Outcome::Win => them.loses_to(),
Outcome::Loss => them.wins_against(),
Outcome::Draw => them.clone(),
};
Self { us, them }
}
}
impl FromStr for Match {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let choices: Vec<&str> = s.split_whitespace().collect();
Ok(Match {
them: Choice::from_str(choices[0]).unwrap(),
us: Choice::from_str(choices[1]).unwrap(),
})
}
}
enum Outcome {
Loss,
Draw,
Win,
}
impl FromStr for Outcome {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"X" => Ok(Outcome::Loss),
"Y" => Ok(Outcome::Draw),
"Z" => Ok(Outcome::Win),
_ => Err(()),
}
}
}
#[derive(PartialEq, Clone)]
enum Choice {
Rock = 1,
Paper = 2,
Scissors = 3,
}
impl Choice {
pub fn wins_against(&self) -> Choice {
match self {
Choice::Rock => Choice::Scissors,
Choice::Paper => Choice::Rock,
Choice::Scissors => Choice::Paper,
}
}
pub fn loses_to(&self) -> Choice {
match self {
Choice::Rock => Choice::Paper,
Choice::Paper => Choice::Scissors,
Choice::Scissors => Choice::Rock,
}
}
}
impl FromStr for Choice {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"A" | "X" => Ok(Choice::Rock),
"B" | "Y" => Ok(Choice::Paper),
"C" | "Z" => Ok(Choice::Scissors),
_ => Err(()),
}
}
}
pub fn part1(input: &str) -> String {
let total: i32 = input
.lines()
.map(|line| Match::from_str(line).unwrap().get_score())
.sum();
format!("{total}")
}
pub fn part2(input: &str) -> String {
let total: i32 = input
.lines()
.map(|line| Match::from_instructions(line).get_score())
.sum();
format!("{total}")
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = r#"A Y
B X
C Z"#;
#[test]
fn test_part1() {
assert_eq!(part1(INPUT), "15");
}
#[test]
fn test_part2() {
assert_eq!(part2(INPUT), "12");
}
}