main.rs (1992B)
1 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
2 enum Shape {
3 Rock = 1,
4 Paper = 2,
5 Scissors = 3,
6 }
7
8 #[derive(Clone, Copy)]
9 enum Outcome {
10 Win = 6,
11 Draw = 3,
12 Lose = 0,
13 }
14
15 impl Shape {
16 fn from_str(s: &str) -> Option<Self> {
17 match s {
18 "A" | "X" => Some(Self::Rock),
19 "B" | "Y" => Some(Self::Paper),
20 "C" | "Z" => Some(Self::Scissors),
21 _ => None,
22 }
23 }
24
25 fn winning_shape(&self) -> Self {
26 match self {
27 Self::Rock => Self::Paper,
28 Self::Paper => Self::Scissors,
29 Self::Scissors => Self::Rock,
30 }
31 }
32
33 fn losing_shape(&self) -> Self {
34 match self {
35 Self::Rock => Self::Scissors,
36 Self::Paper => Self::Rock,
37 Self::Scissors => Self::Paper,
38 }
39 }
40
41 fn get_outcome(&self, other: &Self) -> Outcome {
42 if self == &other.winning_shape() {
43 Outcome::Win
44 } else if self == &other.losing_shape() {
45 Outcome::Lose
46 } else {
47 Outcome::Draw
48 }
49 }
50 }
51
52 fn main() {
53 let input = std::fs::read_to_string("input.txt")
54 .unwrap()
55 .trim()
56 .split("\n")
57 .map(|x| x.split(' ').map(|x| Shape::from_str(x).unwrap()).collect())
58 .collect::<Vec<Vec<Shape>>>();
59 // 11150
60 println!("Part 1: {}", part_1(&input));
61 // 8295
62 println!("Part 2: {}", part_2(&input));
63 }
64
65 fn part_1(input: &Vec<Vec<Shape>>) -> i32 {
66 (0..input.len())
67 .map(|i| input[i][1] as i32 + input[i][1].get_outcome(&input[i][0]) as i32)
68 .sum()
69 }
70
71 fn part_2(input: &Vec<Vec<Shape>>) -> i32 {
72 (0..input.len())
73 .map(|i| match input[i][1] {
74 Shape::Rock => Outcome::Lose as i32 + input[i][0].losing_shape() as i32,
75 Shape::Paper => Outcome::Draw as i32 + input[i][0] as i32,
76 Shape::Scissors => Outcome::Win as i32 + input[i][0].winning_shape() as i32,
77 })
78 .sum()
79 }