Last active
April 6, 2021 08:34
-
-
Save DeBukkIt/5c5e7fd97c62e183b6ca0e4b310cac95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#define arr_size 8 | |
void solve(); | |
bool elementsUnique(int *arr, int size); | |
int compare(const void* a, const void* b); | |
bool isPairwiseDifferent(int *arr, int p, int size); | |
int main() { | |
printf("(s,e,n,d,m,o,r,y)\n"); | |
solve(); | |
return 0; | |
} | |
/* | |
* 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 | |
*/ | |
void solve() { | |
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++) { | |
// ----------------------------------------------------- | |
bool sumOK = s*1000 + e*100 + n*10 + d + | |
m*1000 + o*100 + r*10 + e == | |
m*10000 + o*1000 + n*100 + e*10 + y; | |
if(sumOK) { | |
int result[arr_size] = {s,e,n,d,m,o,r,y}; | |
if(elementsUnique(result, arr_size)) { | |
// Print result | |
printf("%s", "("); | |
for(int i = 0; i < arr_size-1; i++) { | |
printf("%i,", result[i]); | |
} | |
printf("%i%s", result[arr_size-1], ")"); | |
return; | |
} | |
} | |
// ----------------------------------------------------- | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
bool elementsUnique(int *arr, int size) { | |
// 1. copy | |
int copy[size]; | |
for(int i = 0; i < size; i++) { | |
copy[i] = arr[i]; | |
} | |
// 2. sort | |
qsort(copy, size, sizeof(int), compare); | |
// 3. compare pairwise | |
return isPairwiseDifferent(copy, 0, size); | |
} | |
int compare(const void* a, const void* b) { | |
int int_a = *((int*) a); | |
int int_b = *((int*) b); | |
if (int_a == int_b) return 0; | |
else if (int_a < int_b) return -1; | |
else return 1; | |
} | |
bool isPairwiseDifferent(int *arr, int p, int size) { | |
if(p == size - 1) { | |
return true; | |
} | |
return arr[p] != arr[p+1] && isPairwiseDifferent(arr, p+1, size); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment