Editorial for Numerology


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.
by: doncho

Sample solution in:

JavaScript

const transform = (a, b) => {
    return (a + b) * (a ^ b) % 10;
}

const defaultCounts = Array.from({
    length: 10
}, () => 0);

const solve = (digits, counts = [...defaultCounts]) => {
    if (digits.length === 1) {
        const digit = digits[0];
        counts[digit] = counts[digit] || 0;
        counts[digit] += 1;
        return;
    }

    for (let i = 0; i < digits.length - 1; i += 1) {
        const a = digits[i];
        const b = digits[i + 1];
        const result = transform(a, b);
        const newDigits = [...digits];
        newDigits.splice(i, 2, result);
        solve(newDigits, counts);
    }

    return counts.map((digit) => digit || 0);
};

print(
    solve(gets()
        .split('')
        .map(Number))
    .join(' ')
);

Java

public class NumerologySolution {
    private static void fakeInput() {
        String test = "18790314";
        System.setIn(new ByteArrayInputStream(test.getBytes()));
    }

    private static int[] result;

    public static int[] numerology() {
        fakeInput();
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();

        result = new int[10];
        for (int i : result) {
            i = 0;
        }

        int[] digits = new int[8];
        int i = 7;
        while (0 < x) {
            digits[i] = x % 10;
            x /= 10;
            i--;
        }

        countDigits(digits);

        return result;
    }

    private static void countDigits(int[] digits) {
        if (digits.length == 1) {
            result[digits[0]]++;
            return;
        }

        for (int i = 0; i < digits.length - 1; i++) {
            int[] newDigits = new int[digits.length - 1];
            for (int j = 0; j < i; j++) {
                newDigits[j] = digits[j];
            }
            newDigits[i] = calcDigit(digits[i], digits[i + 1]);
            for (int j = i + 2; j < digits.length; j++) {
                newDigits[j - 1] = digits[j];
            }
            countDigits(newDigits);
        }
    }

    private static int calcDigit(int x, int y) {
        return ((x + y) * (x ^ y)) % 10;
    }
}

Comments

There are no comments at the moment.