Day 2. Much easier. Getting the hang of it

This commit is contained in:
Dustin Swan 2022-12-02 12:07:26 -05:00
parent 7bf7727b6c
commit 3eacd6d75d
No known key found for this signature in database
GPG key ID: AB49BD6B2B3A6377
5 changed files with 2564 additions and 0 deletions

46
day2/src/main.rs Normal file
View file

@ -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)
}