use crate::LineResult;
use arrayvec::ArrayVec;

const FREQ_TABLE: [usize; 50] = {
    let mut tab = [0; 50];
    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 parts = line.split('|');
    let input = parts.next().unwrap();

    let mut counts = [0; 7];
    for c in input.bytes() {
        if (b'a'..=b'g').contains(&c) {
            counts[c as usize - b'a' as usize] += 1;
        }
    }

    let digits = parts
        .next()
        .unwrap()
        .trim_start()
        .split(' ')
        .map(|s| s.bytes().map(|c| counts[c as usize - b'a' as usize]).sum())
        .map(|n: usize| FREQ_TABLE[n])
        .collect::<ArrayVec<_, 4>>()
        .into_inner()
        .unwrap();

    LineResult {
        unique_digits: digits.iter().filter(|d| [1, 4, 7, 8].contains(d)).count(),
        number: digits.iter().fold(0, |acc, d| acc * 10 + d),
    }
}
