From 92aba2db955d47aa0ba96a83dcae8a174c85e1ed Mon Sep 17 00:00:00 2001 From: Xiretza Date: Thu, 9 Dec 2021 18:03:39 +0100 Subject: [PATCH] 2021 day8/rust: use ArrayVec This avoids an allocation and, more importantly, turns `digits` into a fixed size array, allowing the final calculations to be unrolled completely. --- 2021/day8/day8_rs/Cargo.toml | 1 + 2021/day8/day8_rs/src/v2.rs | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/2021/day8/day8_rs/Cargo.toml b/2021/day8/day8_rs/Cargo.toml index 4d61240..3e58a08 100644 --- a/2021/day8/day8_rs/Cargo.toml +++ b/2021/day8/day8_rs/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +arrayvec = "0.7.2" [dev-dependencies] criterion = "0.3.5" diff --git a/2021/day8/day8_rs/src/v2.rs b/2021/day8/day8_rs/src/v2.rs index 135fa54..df958d1 100644 --- a/2021/day8/day8_rs/src/v2.rs +++ b/2021/day8/day8_rs/src/v2.rs @@ -1,4 +1,5 @@ use crate::LineResult; +use arrayvec::ArrayVec; const FREQ_TABLE: [usize; 50] = { let mut tab = [0; 50]; @@ -28,14 +29,16 @@ pub fn unscramble(line: &str) -> LineResult { } } - let digits: Vec<_> = parts + let digits = parts .next() .unwrap() .trim() .split(' ') .map(|s| s.bytes().map(|c| counts[c as usize - b'a' as usize]).sum()) .map(|n: usize| FREQ_TABLE[n]) - .collect(); + .collect::>() + .into_inner() + .unwrap(); LineResult { unique_digits: digits.iter().filter(|d| [1, 4, 7, 8].contains(d)).count(),