You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.5 KiB
Rust

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(score_part1).collect();
let final_score_part1: usize = scores.iter().sum();
println!("Game 1 score: {final_score_part1}");
let scores2: Vec<usize> = turns.iter().map(score_part2).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)
}