use crate::LineResult;

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: Vec<_> = 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();

    LineResult {
        unique_digits: digits.iter().filter(|d| [1, 4, 7, 8].contains(d)).count(),
        number: digits
            .iter()
            .rev()
            .scan(1, |mul, &d| {
                let ret = Some(d * *mul);
                *mul *= 10;
                ret
            })
            .sum(),
    }
}
