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.
This commit is contained in:
Xiretza 2021-12-09 18:03:39 +01:00
parent a231883ea7
commit 92aba2db95
2 changed files with 6 additions and 2 deletions

View file

@ -6,6 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
arrayvec = "0.7.2"
[dev-dependencies] [dev-dependencies]
criterion = "0.3.5" criterion = "0.3.5"

View file

@ -1,4 +1,5 @@
use crate::LineResult; use crate::LineResult;
use arrayvec::ArrayVec;
const FREQ_TABLE: [usize; 50] = { const FREQ_TABLE: [usize; 50] = {
let mut tab = [0; 50]; let mut tab = [0; 50];
@ -28,14 +29,16 @@ pub fn unscramble(line: &str) -> LineResult {
} }
} }
let digits: Vec<_> = parts let digits = parts
.next() .next()
.unwrap() .unwrap()
.trim() .trim()
.split(' ') .split(' ')
.map(|s| s.bytes().map(|c| counts[c as usize - b'a' as usize]).sum()) .map(|s| s.bytes().map(|c| counts[c as usize - b'a' as usize]).sum())
.map(|n: usize| FREQ_TABLE[n]) .map(|n: usize| FREQ_TABLE[n])
.collect(); .collect::<ArrayVec<_, 4>>()
.into_inner()
.unwrap();
LineResult { LineResult {
unique_digits: digits.iter().filter(|d| [1, 4, 7, 8].contains(d)).count(), unique_digits: digits.iter().filter(|d| [1, 4, 7, 8].contains(d)).count(),