From 7df9855f2da22b5cbb14ee5d862e86726c2f8438 Mon Sep 17 00:00:00 2001 From: omagdy7 Date: Sun, 3 Dec 2023 00:13:05 +0200 Subject: Switched to a more idiomatic functional approach --- 2023/Rust/src/day2.rs | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/2023/Rust/src/day2.rs b/2023/Rust/src/day2.rs index 6e5b909..c93d6dd 100644 --- a/2023/Rust/src/day2.rs +++ b/2023/Rust/src/day2.rs @@ -42,26 +42,15 @@ impl From<&str> for Game { } fn solve_part_one(data: &str) -> u32 { - let mut games: Vec = vec![]; - for game in data.lines() { - games.push(Game::from(game)); - } - let mut ans: u32 = 0; - for game in games { - if game.red <= 12 && game.green <= 13 && game.blue <= 14 { - ans += game.id as u32; - } - } - ans + data.lines() + .map(|game| Game::from(game)) + .filter(|game| game.red <= 12 && game.green <= 13 && game.blue <= 14) + .fold(0, |acc, game| acc + game.id as u32) } fn solve_part_two(data: &str) -> u32 { - let mut games: Vec = vec![]; - for game in data.lines() { - games.push(Game::from(game)); - } - games - .iter() + data.lines() + .map(|game| Game::from(game)) .map(|game| game.red * game.blue * game.green) .sum::() } -- cgit v1.2.3