-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgo.java
More file actions
72 lines (71 loc) · 2.43 KB
/
algo.java
File metadata and controls
72 lines (71 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.*;
public class algo {
static boolean flag = false;
public static int makenum(HashMap<Character,Integer> map,String str){
StringBuilder sb = new StringBuilder();
for(int i=0;i<str.length();i++){
sb.append(map.get(str.charAt(i)));
}
String num = sb.toString();
return (Integer.parseInt(num));
}
public static void helper(HashMap<Character,Integer> map,String unique,boolean[] used,String[] words,String result,int target){
//base case
if(target==unique.length()){
int sum = 0;
for(int i=0;i<words.length;i++){
sum = sum + makenum(map,words[i]);
}
int res = makenum(map,result);
if(sum==res){
System.out.println("SUM:"+sum);
flag=true;
System.out.println(map);
}
return;
}
char ch = unique.charAt(target);
for(int i=0;i<=9;i++){
if(used[i]==false){
map.put(ch,i);
used[i] = true;
helper(map,unique,used,words,result,target+1);
//bactracking step (undo changes)
used[i] = false;
}
}
}
public static boolean isSolvable(String[] words, String result) {
HashMap<Character,Integer> map = new HashMap<>();
StringBuilder sb = new StringBuilder();
for(int i=0;i<words.length;i++){
for(int j=0;j<words[i].length();j++){
char ch = words[i].charAt(j);
if(map.containsKey(ch)==false){
map.put(ch,-1);
sb.append(ch);
}
}
}
for(int i=0;i<result.length();i++){
char ch = result.charAt(i);
if(map.containsKey(ch)==false){
map.put(ch,-1);
sb.append(ch);
}
}
String unique = sb.toString();
System.out.println("Unique: "+unique);
if(unique.length()>10) return false;
boolean used[] = new boolean[10];
System.out.println(Arrays.toString(used));
helper(map,unique,used,words,result,0);
System.out.println(map.size());
return flag;
}
public static void main(String[] args) {
String words[] = {"SEND","MORE"};
String res = "MONEY";
System.out.println(isSolvable(words, res));
}
}