From f0b8e240a7e1dcc79c3f2109c6365dbbf7c67b46 Mon Sep 17 00:00:00 2001 From: cos Date: Wed, 8 Dec 2021 21:51:54 +0100 Subject: Simplify set operations of 2021day08 Performing operations on sets using operators, rather than the less ergonomic replaced methods, results readability improvements. --- 2021/rust/day08/src/main.rs | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/2021/rust/day08/src/main.rs b/2021/rust/day08/src/main.rs index f4e44bd..0eeb904 100644 --- a/2021/rust/day08/src/main.rs +++ b/2021/rust/day08/src/main.rs @@ -144,9 +144,7 @@ fn find_digits(input: &[Digit]) -> Result>> { } for unique_segments in [1, 4, 7, 8].into_iter() { // Digit 1 is found by unique number of segments, as in part 1. - // Digit 4 is found by unique number of segments, as in part 1. - // Digit 7 is found by unique number of segments, as in part 1. - // Digit 8 is found by unique number of segments, as in part 1. + // The same is true for Digit 4, Digit 7 and Digit 8. unknown.clone().into_iter().map(|d| if d.inner.len() == segment_count[unique_segments] { unknown.remove(&d); digits[unique_segments] = Some(d); @@ -168,15 +166,12 @@ fn find_digits(input: &[Digit]) -> Result>> { digits[0] = unknown.clone().into_iter().filter(|d| { if let (Some(one), Some(three), Some(four), Some(eight)) = (&digits[1], &digits[3], &digits[4], &digits[8]) - { - let set_a = four.inner.difference(&(one.inner)).cloned().collect(); - let set_b = three.inner.intersection(&set_a).cloned().collect(); - let set_c = eight.inner.difference(&set_b).cloned().collect(); - if d.inner == set_c { - unknown.remove(d); - return true - } + { + if d.inner == &eight.inner - &(&three.inner & &(&four.inner - &one.inner)) { + unknown.remove(d); + return true } + } false }).last(); digits[9] = unknown.clone().into_iter().filter(|d| { @@ -200,9 +195,7 @@ fn find_digits(input: &[Digit]) -> Result>> { // Digit 2 is the one with zero overlap with the difference of Digit 4 - Digit 3. digits[2] = unknown.clone().into_iter().filter(|d| { if let (Some(three), Some(four)) = (&digits[3], &digits[4]) { - let set_a = four.inner.difference(&(three.inner)).cloned().collect(); - let set_b: HashSet = d.inner.intersection(&set_a).cloned().collect(); - if set_b.is_empty() { + if (&d.inner & &(&four.inner - &three.inner)).is_empty() { unknown.remove(d); return true } -- cgit v1.2.3