Arithmetic Puzzle Solution
unknown
plain_text
2 years ago
2.4 kB
10
Indexable
class Solution { public boolean isSolvable(String[] words, String result) { Integer[] values = new Integer[26]; Character[] characterAssigned = new Character[10]; List<String> allWords = new ArrayList<>(Arrays.asList(words)); allWords.add(result); return generateSolution(allWords, 0 , 0, values, characterAssigned); } private boolean generateSolution(List<String> words, int index , int indexInsideWord, Integer[] values, Character[] characterAssigned) { if(index == words.size()) { return isEquationSatisfied(words, values); } boolean f = false; String word = words.get(index); if(indexInsideWord < word.length()) { char c = word.charAt(indexInsideWord); if(values[c - 'A'] == null) { for(int i = 0; i <= 9; i++) { if(characterAssigned[i] == null) { values[c - 'A'] = i; characterAssigned[i] = c; f = generateSolution(words, index, indexInsideWord + 1, values,characterAssigned); if(f == true) { return true; } values[c - 'A'] = null; characterAssigned[i] = null; } } } else { f = generateSolution(words, index, indexInsideWord + 1, values,characterAssigned); } } else { f = generateSolution(words, index + 1, 0, values, characterAssigned); } return f; } private boolean isEquationSatisfied(List<String> words, Integer[] values) { int lsum = 0; int num; for(int i = 0; i < words.size() - 1; i++) { num = 0; String word = words.get(i); for(int j = word.length() - 1; j >= 0; j--) { char c = word.charAt(j); num = num*10 + values[c - 'A']; } lsum+=num; } String lastWord = words.get(words.size() - 1); num = 0; for(int j = lastWord.length() - 1; j >= 0; j--) { char c = lastWord.charAt(j); num = num*10 + values[c - 'A']; } return (lsum == num); } }
Editor is loading...