advent-of-code/2021/day8/rust/src/v3.rs
2022-12-01 19:24:06 +01:00

64 lines
1.3 KiB
Rust

use crate::LineResult;
const FREQ_TABLE: [usize; 256] = {
let mut tab = [0; 256];
tab[17] = 1;
tab[25] = 7;
tab[30] = 4;
tab[34] = 2;
tab[37] = 5;
tab[39] = 3;
tab[41] = 6;
tab[42] = 0;
tab[45] = 9;
tab[49] = 8;
tab
};
#[must_use]
#[inline]
pub fn unscramble(line: &str) -> LineResult {
let mut bytes = line.bytes();
let mut counts = [0; 7];
loop {
match bytes.next().unwrap() {
c @ b'a'..=b'g' => {
counts[c as usize - b'a' as usize] += 1;
}
b'|' => break,
_ => {}
}
}
bytes.next();
let mut freq = 0;
let mut unique_digits = 0;
let mut number = 0;
loop {
let c = bytes.next();
match c {
Some(b' ') | None => {
let digit = FREQ_TABLE[freq & 0xff];
if [1, 4, 7, 8].contains(&digit) {
unique_digits += 1;
}
number = number * 10 + digit;
freq = 0;
if c.is_none() {
break;
}
}
Some(c @ b'a'..=b'g') => {
freq += counts[c as usize - b'a' as usize];
},
Some(_) => {}
}
}
LineResult {
unique_digits,
number,
}
}