Skip to content

Instantly share code, notes, and snippets.

@DeBukkIt
Last active April 2, 2021 11:06
Show Gist options
  • Save DeBukkIt/1f2890e26838e55ba72b45866ed6380b to your computer and use it in GitHub Desktop.
Save DeBukkIt/1f2890e26838e55ba72b45866ed6380b to your computer and use it in GitHub Desktop.
Solve SEND+MORE=MONEY puzzle with Java
import java.util.Arrays;
public class SendMoreMoney {
public static void main(String[] args) {
SendMoreMoney smm = new SendMoreMoney();
System.out.println("[s, e, n, d, m, o, r, y]");
System.out.println(Arrays.toString(smm.solve()));
}
/*
* S E N D
* + M O R E
* ------------
* M O N E Y
* where M != 0 and every digit stands for a different (unique) number
*/
private int[] solve() {
int[] result = null;
for(int s = 0; s <= 9; s++) {
for(int e = 0; e <= 9; e++) {
for(int n = 0; n <= 9; n++) {
for(int d = 0; d <= 9; d++) {
for(int m = 1; m <= 9; m++) { // [sic!]
for(int o = 0; o <= 9; o++) {
for(int r = 0; r <= 9; r++) {
for(int y = 0; y <= 9; y++) {
// ------------------------------------------------
// Does sum of SEND and MORE match MONEY?
if( s*1000 + e*100 + n*10 + d
+ m*1000 + o*100 + r*10 + e
== m*10000 + o*1000 + n*100 + e*10 + y) {
// Then put digits into result array
result = new int[] {s,e,n,d,m,o,r,y};
// Check if elements are also unique
if(elementsUnique(result)) {
// True? That's our solution!
return result;
}
// else continue
}
// else continue
// ------------------------------------------------
}
}
}
}
}
}
}
}
// we should never reach this line
return null;
}
private boolean elementsUnique(int[] arr) {
// Make a temporary copy of our result array to keep the order
int[] copyOfArr = new int[arr.length];
System.arraycopy(arr, 0, copyOfArr, 0, arr.length);
// Sort
Arrays.sort(copyOfArr);
// Check for pairwise dissimilarity
return isPairwiseDifferent(copyOfArr, 0);
}
private boolean isPairwiseDifferent(int[] arr, int p) {
if(p == arr.length - 1) {
return true;
}
return arr[p] != arr[p+1] && isPairwiseDifferent(arr, p+1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment