solve 2022 day 02

This commit is contained in:
fuckwit
2023-11-22 23:41:32 +01:00
parent f0a198d6f9
commit 2956bb6ce3
6 changed files with 2596 additions and 1 deletions

View File

@ -21,5 +21,5 @@ fn test_part1() {
#[test]
fn test_part2() {
assert_eq!("4", part2("R8, R4, R4, R8").to_string())
assert_eq!("45000", part2("1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000").to_string())
}

92
src/year2022/day02.rs Normal file
View File

@ -0,0 +1,92 @@
enum Move {
Rock = 1,
Paper = 2,
Scissors = 3
}
enum GameResult {
Loss = 0,
Draw = 3,
Win = 6
}
impl From<&str> for Move {
fn from(value: &str) -> Self {
match value {
"A" | "X" => Self::Rock,
"B" | "Y" => Self::Paper,
"C" | "Z" => Self::Scissors,
_ => unreachable!()
}
}
}
impl From<&str> for GameResult {
fn from(value: &str) -> Self {
match value {
"X" => Self::Loss,
"Y" => Self::Draw,
"Z" => Self::Win,
_ => unreachable!()
}
}
}
fn calc(input: &str, calc: fn(&str, &str) -> u32) -> u32 {
input.lines().map(|l| {
let Some((l, r)) = l.split_once(' ') else {
unreachable!()
};
(calc)(l, r)
}).sum()
}
pub fn part1(input: &str) -> impl std::fmt::Display {
calc(input, |l, r| {
let left = Move::from(l);
let right = Move::from(r);
let result = match (&left, &right) {
(Move::Rock, Move::Rock) => GameResult::Draw,
(Move::Rock, Move::Paper) => GameResult::Win,
(Move::Rock, Move::Scissors) => GameResult::Loss,
(Move::Paper, Move::Rock) => GameResult::Loss,
(Move::Paper, Move::Paper) => GameResult::Draw,
(Move::Paper, Move::Scissors) => GameResult::Win,
(Move::Scissors, Move::Rock) => GameResult::Win,
(Move::Scissors, Move::Paper) => GameResult::Loss,
(Move::Scissors, Move::Scissors) => GameResult::Draw,
};
result as u32 + right as u32
})
}
pub fn part2(input: &str) -> impl std::fmt::Display {
calc(input, |l, r| {
let left = Move::from(l);
let result = GameResult::from(r);
let play = match (&left, &result) {
(Move::Rock, GameResult::Loss) => Move::Scissors,
(Move::Rock, GameResult::Draw) => Move::Rock,
(Move::Rock, GameResult::Win) => Move::Paper,
(Move::Paper, GameResult::Loss) => Move::Rock,
(Move::Paper, GameResult::Draw) => Move::Paper,
(Move::Paper, GameResult::Win) => Move::Scissors,
(Move::Scissors, GameResult::Loss) => Move::Paper,
(Move::Scissors, GameResult::Draw) => Move::Scissors,
(Move::Scissors, GameResult::Win) => Move::Rock,
};
result as u32 + play as u32
})
}
#[test]
fn test_part1() {
assert_eq!("15", part1("A Y\nB X\nC Z").to_string())
}
#[test]
fn test_part2() {
assert_eq!("12", part2("A Y\nB X\nC Z").to_string())
}