Day 2. Much easier. Getting the hang of it
parent
7bf7727b6c
commit
3eacd6d75d
@ -0,0 +1,7 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 3
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "day2"
|
||||||
|
version = "0.1.0"
|
@ -0,0 +1,8 @@
|
|||||||
|
[package]
|
||||||
|
name = "day2"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,46 @@
|
|||||||
|
use std::fs;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let contents = fs::read_to_string("data.txt").expect("Failed to read file");
|
||||||
|
let lines = contents.trim().lines();
|
||||||
|
let turns: Vec<(&str, &str)> = lines
|
||||||
|
.map(|x| (x.get(0..1).unwrap(), x.get(2..3).unwrap()))
|
||||||
|
.collect();
|
||||||
|
let scores: Vec<usize> = turns.iter().map(|&x| score_part1(x)).collect();
|
||||||
|
let final_score_part1: usize = scores.iter().sum();
|
||||||
|
println!("Game 1 score: {final_score_part1}");
|
||||||
|
|
||||||
|
let scores2: Vec<usize> = turns.iter().map(|&x| score_part2(x)).collect();
|
||||||
|
let final_score_part2: usize = scores2.iter().sum();
|
||||||
|
println!("Game 2 score: {:?}", final_score_part2);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_points(play: &str) -> usize {
|
||||||
|
match play {
|
||||||
|
"X" => 1,
|
||||||
|
"Y" => 2,
|
||||||
|
_ => 3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn win_points(turn: (&str, &str)) -> usize {
|
||||||
|
match turn {
|
||||||
|
("C", "X") | ("A", "Y") | ("B", "Z") => 6, // win
|
||||||
|
("A", "X") | ("B", "Y") | ("C", "Z") => 3, // draw
|
||||||
|
_ => 0, // loss
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn score_part1(turn: (&str, &str)) -> usize {
|
||||||
|
win_points(turn) + type_points(turn.1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn score_part2(turn: (&str, &str)) -> usize {
|
||||||
|
let my_move: &str = match turn {
|
||||||
|
("A", "X") | ("B", "Z") | ("C", "Y") => "Z", // lose to rock, win to paper, or draw with scissors -> I play scissors
|
||||||
|
("A", "Y") | ("B", "X") | ("C", "Z") => "X", // draw with rock, lose to paper, win to scissors -> I play rock
|
||||||
|
_ => "Y", // anything else -> I play paper
|
||||||
|
};
|
||||||
|
|
||||||
|
win_points((turn.0, my_move)) + type_points(my_move)
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
A Y
|
||||||
|
B X
|
||||||
|
C Z
|
Loading…
Reference in New Issue