1
0
mirror of https://gitlab.com/MisterBiggs/aoc-2023-rust.git synced 2025-06-15 14:36:50 +00:00

day 2 complete

This commit is contained in:
Anson 2022-12-02 00:10:50 -07:00
parent 6fe29ebc99
commit 3186395692
3 changed files with 2612 additions and 0 deletions

2500
inputs/day2.txt Normal file

File diff suppressed because it is too large Load Diff

110
src/day2.rs Normal file
View File

@ -0,0 +1,110 @@
use itertools::Itertools;
use std::fs;
pub fn run() {
println!("Day 2:");
let input = fs::read_to_string("./inputs/day2.txt").expect("Could not read file");
println!("\tPart 1: {}", part1(&input));
println!("\tPart 2: {}", part2(&input));
}
#[derive(PartialEq, Clone, Copy)]
enum Hand {
Rock = 1,
Paper,
Scissors,
}
#[derive(Clone, Copy)]
enum Outcome {
Lost = 0,
Draw = 3,
Win = 6,
}
fn part1(input: &str) -> usize {
input
.trim()
.split('\n')
.map(|round_str| {
let round = round_str.split_once(' ').unwrap();
let opponent = match round.0 {
"A" => Hand::Rock,
"B" => Hand::Paper,
"C" => Hand::Scissors,
_ => panic!(),
};
let me = match round.1 {
"X" => Hand::Rock,
"Y" => Hand::Paper,
"Z" => Hand::Scissors,
_ => panic!(),
};
let outcome = match (opponent, me) {
(l, r) if l == r => Outcome::Draw,
(Hand::Rock, Hand::Paper) => Outcome::Win,
(Hand::Paper, Hand::Scissors) => Outcome::Win,
(Hand::Scissors, Hand::Rock) => Outcome::Win,
_ => Outcome::Lost,
};
outcome as usize + me as usize
})
.sum()
}
fn part2(input: &str) -> usize {
input
.trim()
.split('\n')
.map(|round_str| {
let round = round_str.split_once(' ').unwrap();
let opponent = match round.0 {
"A" => Hand::Rock,
"B" => Hand::Paper,
"C" => Hand::Scissors,
_ => panic!(),
};
let outcome = match round.1 {
"X" => Outcome::Lost,
"Y" => Outcome::Draw,
"Z" => Outcome::Win,
_ => panic!(),
};
let me = match (outcome, opponent) {
(Outcome::Draw, _) => opponent,
(Outcome::Win, Hand::Rock) => Hand::Paper,
(Outcome::Win, Hand::Paper) => Hand::Scissors,
(Outcome::Win, Hand::Scissors) => Hand::Rock,
(Outcome::Lost, Hand::Rock) => Hand::Scissors,
(Outcome::Lost, Hand::Paper) => Hand::Rock,
(Outcome::Lost, Hand::Scissors) => Hand::Paper,
};
outcome as usize + me as usize
})
.sum()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
let input = "A Y
B X
C Z";
assert_eq!(part1(input), 15);
}
#[test]
fn test_2() {
let input = "A Y
B X
C Z";
assert_eq!(part2(input), 12);
}
}

View File

@ -1,5 +1,7 @@
mod day1;
mod day2;
fn main() {
println!("Running Advent of Code 2022");
day1::run();
day2::run();
}