From 5118d766b3ab134b27458bfde6e9a3fe8c9a36e4 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Sun, 4 Dec 2022 00:00:56 -0600 Subject: [PATCH] Cleaned up a bit --- 2022/rust/src/day4.rs | 59 ++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 37 deletions(-) diff --git a/2022/rust/src/day4.rs b/2022/rust/src/day4.rs index 1300d6d..32917ca 100644 --- a/2022/rust/src/day4.rs +++ b/2022/rust/src/day4.rs @@ -6,47 +6,32 @@ fn main() { println!("Part 2: {}", part2(&input)); } -fn part1(input: &str) -> i32 { - let mut r = 0; - for l in input.lines() { - let mut c = l.split(","); - let p1 = c.next().unwrap(); - let p2 = c.next().unwrap(); - let mut p1c = p1.split("-"); - let p1n1 = p1c.next().unwrap().parse::().unwrap(); - let p1n2 = p1c.next().unwrap().parse::().unwrap(); - let mut p2c = p2.split("-"); - let p2n1 = p2c.next().unwrap().parse::().unwrap(); - let p2n2 = p2c.next().unwrap().parse::().unwrap(); +fn nums(input: &str) -> Vec { + input + .replace(",", "-") + .split("-") + .map(|s| s.parse::().unwrap()) + .collect() +} - if (p1n1 <= p2n1 && p1n2 >= p2n2) || (p2n1 <= p1n1 && p2n2 >= p1n2) { - r += 1 - } - } - r +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 part2(input: &str) -> i32 { - let mut r = 0; - for l in input.lines() { - println!("{}", l); - let mut c = l.split(","); - let p1 = c.next().unwrap(); - let p2 = c.next().unwrap(); - let mut p1c = p1.split("-"); - let x1 = p1c.next().unwrap().parse::().unwrap(); - let x2 = p1c.next().unwrap().parse::().unwrap(); - let mut p2c = p2.split("-"); - let y1 = p2c.next().unwrap().parse::().unwrap(); - let y2 = p2c.next().unwrap().parse::().unwrap(); - - println!("{}-{} , {}-{}", x1, x2, y1, y2); - if x1 <= y2 && y1 <= x2 { - r += 1; - println!("overlap"); - } - } - r + input + .lines() + .map(|l| { + let n = nums(l); + (n[0] <= n[3] && n[2] <= n[1]) as i32 + }) + .sum() } #[cfg(test)]