From e7f1e50aa6b10fdf771b9474cae743f0ac587f04 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Fri, 2 Dec 2022 07:44:42 +0100 Subject: [PATCH] 2022 day2/rust: cleanup --- 2022/day2/rust/src/main.rs | 53 ++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/2022/day2/rust/src/main.rs b/2022/day2/rust/src/main.rs index c2a2a99..9c4646b 100644 --- a/2022/day2/rust/src/main.rs +++ b/2022/day2/rust/src/main.rs @@ -1,3 +1,4 @@ +use core::fmt; use std::{ io::{stdin, Read}, str::FromStr, @@ -91,31 +92,39 @@ impl FromStr for Outcome { } } +fn get_score(s: &str, f: F) -> u64 +where + F: Fn(Rps, Rhs) -> (Rps, Outcome), + Rhs: FromStr, + ::Err: fmt::Debug, +{ + s.lines() + .map(|line| { + let mut parts = line.split_whitespace(); + + let other: Rps = parts.next().unwrap().parse().unwrap(); + let rhs = parts.next().unwrap().parse().unwrap(); + + let (me, outcome) = f(other, rhs); + me.score() + outcome.score() + }) + .sum() +} + fn main() { let mut data = String::new(); stdin().read_to_string(&mut data).unwrap(); - let mut sum1 = 0u64; - let mut sum2 = 0u64; + println!( + "{}", + get_score(&data, |other, me| (me, me.outcome_against(other))) + ); - for line in data.lines() { - let parts: Vec<_> = line.split_whitespace().collect(); - let other: Rps = parts[0].parse().unwrap(); - - { - let me: Rps = parts[1].parse().unwrap(); - let outcome = me.outcome_against(other); - - sum1 += me.score() + outcome.score(); - } - { - let outcome = parts[1].parse().unwrap(); - let me = other.with_outcome(outcome); - - sum2 += me.score() + outcome.score(); - } - } - - println!("{}", sum1); - println!("{}", sum2); + println!( + "{}", + get_score(&data, |other, outcome| ( + other.with_outcome(outcome), + outcome + )) + ); }