Untitled

 avatar
unknown
plain_text
5 months ago
2.9 kB
3
Indexable
public static int solution(String[] crypt) {
        // Extract unique letters
        Set<Character> uniqueLetters = new HashSet<>();
        for (String word : crypt) {
            for (char c : word.toCharArray()) {
                uniqueLetters.add(c);
            }
        }

        // If there are more than 10 unique letters, return 0
        if (uniqueLetters.size() > 10) {
            return 0;
        }

        // Convert the set of unique letters to a list
        List<Character> letters = new ArrayList<>(uniqueLetters);
        int validSolutions = 0;

        // Generate all permutations of digits (0-9)
        int[] digits = new int[10];
        for (int i = 0; i < 10; i++) {
            digits[i] = i;
        }

        // Call the function to count valid solutions
        validSolutions = countValidSolutions(crypt, letters, new boolean[10], new int[letters.size()], 0);
        
        return validSolutions;
    }

    private static int countValidSolutions(String[] crypt, List<Character> letters, boolean[] used, int[] mapping, int index) {
        if (index == letters.size()) {
            // All letters are mapped, check the solution
            return isValidSolution(crypt, letters, mapping) ? 1 : 0;
        }

        int count = 0;
        for (int i = 0; i < 10; i++) {
            if (!used[i]) {
                // Mark the digit as used
                used[i] = true;
                mapping[index] = i;

                // Recurse to the next letter
                count += countValidSolutions(crypt, letters, used, mapping, index + 1);

                // Backtrack
                used[i] = false;
            }
        }
        return count;
    }

    private static boolean isValidSolution(String[] crypt, List<Character> letters, int[] mapping) {
        // Create a mapping from letters to digits
        int[] letterToDigit = new int[26];
        for (int i = 0; i < letters.size(); i++) {
            letterToDigit[letters.get(i) - 'A'] = mapping[i];
        }

        // Check leading zero constraint
        for (String word : crypt) {
            if (letterToDigit[word.charAt(0) - 'A'] == 0 && word.length() > 1) {
                return false; // Leading zero in a multi-digit number
            }
        }

        // Convert words to numbers
        long num1 = convertToNumber(crypt[0], letterToDigit);
        long num2 = convertToNumber(crypt[1], letterToDigit);
        long num3 = convertToNumber(crypt[2], letterToDigit);

        // Check if the equation holds true
        return num1 + num2 == num3;
    }

    private static long convertToNumber(String word, int[] letterToDigit) {
        long number = 0;
        for (char c : word.toCharArray()) {
            number = number * 10 + letterToDigit[c - 'A'];
        }
        return number;
    }
Editor is loading...
Leave a Comment