1+ import java .util .ArrayList ;
2+ import java .util .Arrays ;
3+ import java .util .Collections ;
4+ import java .util .LinkedHashMap ;
5+ import java .util .LinkedHashSet ;
6+ import java .util .List ;
7+ import java .util .Map ;
8+ import java .util .Optional ;
9+ import java .util .Set ;
10+ import java .util .stream .Collectors ;
11+
12+ public class Alphametics {
13+ private final List <String > wordsToSum ;
14+ private final String wordResult ;
15+
16+ Alphametics (String userInput ) {
17+ String [] questionAndAnswer = userInput .split ("==" );
18+ wordsToSum = Arrays .stream (questionAndAnswer [0 ].split ("\\ +" ))
19+ .map (String ::new )
20+ .map (String ::trim )
21+ .collect (Collectors .collectingAndThen (Collectors .toList (), Collections ::unmodifiableList ));
22+ wordResult = questionAndAnswer [1 ].trim ();
23+ }
24+
25+ Map <Character , Integer > solve () throws UnsolvablePuzzleException {
26+ AlphameticsRecursion solver = new AlphameticsRecursion (getDistinctCharacters ());
27+ solver .generate ();
28+ return solver .get ().orElseThrow (UnsolvablePuzzleException ::new );
29+ }
30+
31+ /**
32+ * Returns the list of distinct characters in this alphametic puzzle.
33+ */
34+ private List <Character > getDistinctCharacters () {
35+ Set <Character > distinctCharacters = new LinkedHashSet <>();
36+ wordsToSum .forEach (word -> distinctCharacters .addAll (toChar (word )));
37+ distinctCharacters .addAll (toChar (wordResult ));
38+
39+ return new ArrayList <>(distinctCharacters );
40+ }
41+
42+ private List <Character > toChar (String toChar ) {
43+ return toChar .chars ()
44+ .mapToObj (c -> (char ) c )
45+ .collect (Collectors .toList ());
46+ }
47+
48+ private class AlphameticsRecursion {
49+ private final List <Character > characters ;
50+ private LinkedHashMap <Character , Integer > validPermutation ;
51+
52+ private AlphameticsRecursion (List <Character > characters ) {
53+ this .characters = characters ;
54+ }
55+
56+ private void generate () {
57+ generate (new LinkedHashMap <>(), 0 , new boolean [10 ]);
58+ }
59+
60+ private void generate (LinkedHashMap <Character , Integer > permutation , int index , boolean [] isDigitsUsed ) {
61+ // base case
62+ if (index == characters .size ()) {
63+ if (!isLeadingDigitZero (permutation ) && isSumTally (permutation )) {
64+ validPermutation = new LinkedHashMap <>(permutation );
65+ }
66+ return ;
67+ }
68+
69+ for (int i = 0 ; i <= 9 ; i ++) { // loop through digits 0 to 9
70+ if (isDigitsUsed [i ]) {
71+ continue ;
72+ }
73+
74+ permutation .put (characters .get (index ), i );
75+ isDigitsUsed [i ] = true ;
76+ generate (permutation , index + 1 , isDigitsUsed );
77+ isDigitsUsed [i ] = false ;
78+ }
79+ }
80+
81+ private Optional <LinkedHashMap <Character , Integer >> get () {
82+ return Optional .ofNullable (validPermutation );
83+ }
84+
85+ /**
86+ * Returns true if the mapping letters to digits using {@code letterToDigit} will result in having zero as a
87+ * leading digit.
88+ */
89+ private boolean isLeadingDigitZero (Map <Character , Integer > letterToDigit ) {
90+ return letterToDigit .keySet ().stream ()
91+ .filter (key -> letterToDigit .get (key ) == 0 ) // Find the character that is mapped to digit 0
92+ .filter (charMappedToZero -> wordResult .charAt (0 ) == charMappedToZero // If the first character in
93+ // wordResult is mapped to 0
94+ || wordsToSum .stream () // If the first character in any of wordsToSum is mapped to 0
95+ .map (word -> word .charAt (0 ))
96+ .anyMatch (character -> character == charMappedToZero ))
97+ .count () == 1 ; // One letter maps to zero and is a leading character
98+ }
99+
100+ /**
101+ * Returns true if the {@code letterToDigit} solves the alphametic puzzle.
102+ */
103+ private boolean isSumTally (Map <Character , Integer > letterToDigit ) {
104+ long actualSum = wordsToSum .stream ()
105+ .mapToLong (word -> mapToNumber (letterToDigit , word ))
106+ .sum ();
107+ long expectedSum = mapToNumber (letterToDigit , wordResult );
108+ return actualSum == expectedSum ;
109+ }
110+
111+ /**
112+ * Returns the long value of {@code word}, mapped using {@code letterToDigit}.
113+ */
114+ private long mapToNumber (Map <Character , Integer > letterToDigit , String word ) {
115+ StringBuilder builder = new StringBuilder ();
116+
117+ for (int i = 0 ; i < word .length (); i ++) {
118+ int digit = letterToDigit .get (word .charAt (i ));
119+ builder .append (digit );
120+ }
121+
122+ return Long .parseLong (builder .toString ());
123+ }
124+ }
125+ }
0 commit comments