-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.rs
140 lines (118 loc) · 2.95 KB
/
lib.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
135
136
137
138
139
140
use crate::Choice::{PAPER, ROCK, SCISSORS};
use crate::Order::{DRAW, LOSE, WIN};
use std::fs::File;
use std::io::{BufRead, BufReader};
pub fn total_score_1(file: &str) -> Result<i32, Box<dyn std::error::Error>> {
let reader = BufReader::new(File::open(file)?);
let mut score = 0;
for res in reader.lines() {
let line = res?;
let split = line.split(" ").collect::<Vec<&str>>();
score += get_score_1(&to_choice(split[0]), &to_choice(split[1]))
}
Ok(score)
}
fn to_choice(choice: &str) -> Choice {
match choice {
"A" => ROCK,
"B" => PAPER,
"C" => SCISSORS,
"X" => ROCK,
"Y" => PAPER,
_ => SCISSORS,
}
}
#[derive(PartialEq)]
enum Choice {
ROCK,
PAPER,
SCISSORS,
}
fn get_score_1(move1: &Choice, move2: &Choice) -> i32 {
return win_points(move1, move2) + score_choice(move2);
}
fn score_choice(choice: &Choice) -> i32 {
match choice {
ROCK => 1,
PAPER => 2,
SCISSORS => 3,
}
}
fn win_points(move1: &Choice, move2: &Choice) -> i32 {
if move1 == move2 {
return 3;
}
match (move1, move2) {
(ROCK, SCISSORS) => 0,
(ROCK, PAPER) => 6,
(PAPER, ROCK) => 0,
(PAPER, SCISSORS) => 6,
(SCISSORS, PAPER) => 0,
(SCISSORS, ROCK) => 6,
_ => 0,
}
}
pub fn total_score_2(file: &str) -> Result<i32, Box<dyn std::error::Error>> {
let reader = BufReader::new(File::open(file)?);
let mut score = 0;
for res in reader.lines() {
let line = res?;
let split = line.split(" ").collect::<Vec<&str>>();
score += get_score_2(&to_choice(split[0]), &to_order(split[1]))
}
Ok(score)
}
#[derive(PartialEq)]
enum Order {
LOSE,
DRAW,
WIN,
}
fn to_order(choice: &str) -> Order {
match choice {
"X" => LOSE,
"Y" => DRAW,
_ => WIN,
}
}
fn get_score_2(move1: &Choice, order: &Order) -> i32 {
match order {
DRAW => 3 + score_choice(move1),
WIN => {
6 + match move1 {
ROCK => score_choice(&PAPER),
PAPER => score_choice(&SCISSORS),
SCISSORS => score_choice(&ROCK),
}
}
LOSE => match move1 {
ROCK => score_choice(&SCISSORS),
PAPER => score_choice(&ROCK),
SCISSORS => score_choice(&PAPER),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn score_1_unit() {
let result = total_score_1("test.txt");
assert_eq!(result.unwrap(), 15);
}
#[test]
fn score_1_input() {
let result = total_score_1("input.txt");
assert_eq!(result.unwrap(), 11386);
}
#[test]
fn score_2_unit() {
let result = total_score_2("test.txt");
assert_eq!(result.unwrap(), 12);
}
#[test]
fn score_2_input() {
let result = total_score_2("input.txt");
assert_eq!(result.unwrap(), 13600);
}
}