class Puzzle{
String first = "";
String second = "";
String result = "";
Set<Character> set;
public Puzzle(String a, String b, String c){
this.first = a;
this.second = b;
this.result = c;
this.set = getCharSet();
System.out.println(set);
}
int getNumber(String s, Map<Character, Integer> proposedSolution){
int num = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
num = num * 10 + proposedSolution.get(c);
}
return num;
}
boolean checkSolution(Map<Character, Integer> proposedSolution) {
int firstNum = getNumber(first, proposedSolution);
int secondNum = getNumber(second, proposedSolution);
int res = getNumber(result, proposedSolution);
return firstNum + secondNum == res;
}
Set<Character> getCharSet(){
Set<Character> set = new HashSet<Character>();
for(int i = 0; i < first.length(); i++){
set.add(first.charAt(i));
}
for(int i = 0; i < second.length(); i++){
set.add(second.charAt(i));
}
for(int i = 0; i < result.length(); i++){
set.add(result.charAt(i));
}
return set;
}
boolean getNextNum(Map<Character, Integer> proposalMap, Set<Integer> usedDigits, char[] charArr, int pos){
if(pos == charArr.length){
if(checkSolution(proposalMap)){
return true;
}
else{
return false;
}
}
for(int i = 0; i < 10; i++){
if(usedDigits.contains(i)) continue;
usedDigits.add(i);
proposalMap.put(charArr[pos], i);
if(getNextNum(proposalMap, usedDigits, charArr, pos+1)){
return true;
}
usedDigits.remove(i);
}
return false;
}
Map<Character, Integer> solve() {
Map<Character, Integer> map = new HashMap<Character, Integer>();
Set<Integer> digits = new HashSet<>();
char[] charSet = new char[set.size()];
int pos =0;
for(char c : this.set){
charSet[pos++] = c;
}
if(getNextNum(map, digits, charSet, 0)){
return map;
}
else{
return null;
}
}
}