add day 2 solution
This commit is contained in:
parent
10c082a4cf
commit
86f89c286d
|
@ -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<u32> {
|
||||
|
||||
Some(input.lines().map(parse_hand).map(score_hand).sum())
|
||||
|
||||
}
|
||||
|
||||
pub fn part_two(input: &str) -> Option<u32> {
|
||||
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));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
A Y
|
||||
B X
|
||||
C Z
|
Loading…
Reference in New Issue