advent-of-code/2021/day8/rust/src/v3.rs

65 lines
1.3 KiB
Rust
Raw Normal View History

2021-12-08 20:15:42 +01:00
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') => {
2021-12-08 20:15:42 +01:00
freq += counts[c as usize - b'a' as usize];
},
Some(_) => {}
2021-12-08 20:15:42 +01:00
}
}
LineResult {
unique_digits,
number,
}
}