From 8dbd0cf9afe36d4c335c97a3a8f1b430cd60daa1 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Sun, 4 Dec 2022 01:44:06 -0600 Subject: [PATCH] Golf-y --- 2022/rust/src/common.rs | 3 +++ 2022/rust/src/day4.rs | 56 +++++++++++++++-------------------------- 2 files changed, 23 insertions(+), 36 deletions(-) diff --git a/2022/rust/src/common.rs b/2022/rust/src/common.rs index 6ce6d74..d5bb362 100644 --- a/2022/rust/src/common.rs +++ b/2022/rust/src/common.rs @@ -15,3 +15,6 @@ pub fn show_answers(answer1: &impl Debug, answer2: &impl Debug) { println!("Part 1: {:?}", answer1); println!("Part 2: {:?}", answer2); } +pub fn show_both_answers((a, b): &(impl Debug, impl Debug)) { + show_answers(a, b) +} diff --git a/2022/rust/src/day4.rs b/2022/rust/src/day4.rs index 019e59d..abbba74 100644 --- a/2022/rust/src/day4.rs +++ b/2022/rust/src/day4.rs @@ -1,56 +1,40 @@ mod common; -fn main() { - let input = common::day_input(4); - println!("Part 1: {}", part1(&input)); - println!("Part 2: {}", part2(&input)); -} - -fn nums(input: &str) -> Vec { +fn processed_input(input: &str) -> Vec> { input - .split(&['-', ',']) - .map(|s| s.parse::().unwrap()) + .lines() + .map(|l| l.split(&['-', ',']).map(|s| s.parse().unwrap()).collect()) .collect() } -fn part1(input: &str) -> i32 { - input - .lines() - .map(|l| { - let n = nums(l); - ((n[0] <= n[2] && n[1] >= n[3]) || (n[2] <= n[0] && n[3] >= n[1])) as i32 - }) - .sum() +fn both_parts(input: &Vec>) -> (usize, usize) { + input.iter().fold((0, 0), |(a, b), n| { + ( + (a + ((n[0] <= n[2] && n[1] >= n[3]) || (n[2] <= n[0] && n[3] >= n[1])) as usize), + b + ((n[0] <= n[3] && n[2] <= n[1]) as usize), + ) + }) } -fn part2(input: &str) -> i32 { - input - .lines() - .map(|l| { - let n = nums(l); - (n[0] <= n[3] && n[2] <= n[1]) as i32 - }) - .sum() +fn main() { + let input = processed_input(&common::day_input(4)); + common::show_both_answers(&both_parts(&input)) } #[cfg(test)] mod tests { use super::*; - const TEST_INPUT: &str = "2-4,6-8 + #[test] + fn test() { + let input = processed_input( + "2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 -2-6,4-8"; - - #[test] - fn test_part1() { - assert_eq!(part1(TEST_INPUT), 2) - } - - #[test] - fn test_part2() { - assert_eq!(part2(TEST_INPUT), 4) +2-6,4-8", + ); + assert_eq!(both_parts(&input), (2, 4)); } }