From 86f89c286d4148805adddb92753c33b9f7d71a50 Mon Sep 17 00:00:00 2001 From: nihilazo Date: Fri, 2 Dec 2022 18:49:48 +0000 Subject: [PATCH] add day 2 solution --- src/bin/02.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++ src/examples/02.txt | 3 ++ 2 files changed, 81 insertions(+) create mode 100644 src/bin/02.rs create mode 100644 src/examples/02.txt diff --git a/src/bin/02.rs b/src/bin/02.rs new file mode 100644 index 0000000..67a2fd1 --- /dev/null +++ b/src/bin/02.rs @@ -0,0 +1,78 @@ +// scores a hand, where each item in the tuple is one player's throw (1 for rock, 2 for paper, 3 for scissors) +fn score_hand(input: (u32,u32)) -> u32 { + let t = input.0; // them + let m = input.1; // me + let win_value = if t == m { + 3 + } else if (m == 1 && t ==3) || (m == 2 && t == 1) || (m == 3 && t == 2) { // if we win + 6 + } else { + 0 + }; + + input.1 + win_value +} + +// generates a hand according to the rules, where the first item in the tuple is the opponent's throw and the second item is the desired result (win, draw, lose) +fn play_hand(input: (u32, u32)) -> (u32,u32) { + let (t,r) = input; + + if r == 2 { // rule: draw + (t,t) + } else if r == 1 { // rule: lose + (t,if t == 1 {3} else if t == 2 {1} else {2}) + } else { + (t,if t == 1 {2} else if t == 2 {3} else {1}) + } +} + +fn parse_hand(input: &str) -> (u32,u32) { + let (left, right) = input.split_at(1); + let mut numeric_hand : (u32,u32) = (0,0); + match left { + "A" => numeric_hand.0 = 1, + "B" => numeric_hand.0 = 2, + "C" => numeric_hand.0 = 3, + _ => panic!("fuckup!") + } + match right { + " X" => numeric_hand.1 = 1, + " Y" => numeric_hand.1 = 2, + " Z" => numeric_hand.1 = 3, + _ => panic!("fuckup!") + } + numeric_hand +} + +pub fn part_one(input: &str) -> Option { + + Some(input.lines().map(parse_hand).map(score_hand).sum()) + +} + +pub fn part_two(input: &str) -> Option { + Some(input.lines().map(parse_hand).map(play_hand).map(score_hand).sum()) +} + +fn main() { + let input = &advent_of_code::read_file("inputs", 2); + advent_of_code::solve!(1, part_one, input); + advent_of_code::solve!(2, part_two, input); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let input = advent_of_code::read_file("examples", 2); + assert_eq!(part_one(&input), Some(15)); + } + + #[test] + fn test_part_two() { + let input = advent_of_code::read_file("examples", 2); + assert_eq!(part_two(&input), Some(12)); + } +} diff --git a/src/examples/02.txt b/src/examples/02.txt new file mode 100644 index 0000000..25097e8 --- /dev/null +++ b/src/examples/02.txt @@ -0,0 +1,3 @@ +A Y +B X +C Z \ No newline at end of file