Voici une solution simple pour imprimer et évaluer toutes les combinaisons des 4 opérateurs +
, -
, *
y /
entre les chiffres. Pour ce code, tous les opérateurs ont la même préséance.
#include <stdio.h>
#include <stdlib.h>
void print_combination(unsigned mask, int *values, int n) {
int x = values[0];
printf("%d", values[0]);
for (int i = 1; i < n; i++, mask /= 4) {
switch (mask % 4) {
case 0: x += values[i]; printf(" + %d", values[i]); break;
case 1: x -= values[i]; printf(" - %d", values[i]); break;
case 2: x *= values[i]; printf(" * %d", values[i]); break;
case 3: x /= values[i]; printf(" / %d", values[i]); break;
}
}
printf(" = %d\n", x);
}
int main(int argc, char *argv[]) {
int n = argc - 1;
int values[n];
for (int i = 0; i < n; i++) {
values[i] = strtol(argv[i + 1], NULL, 0);
}
for (unsigned i = 0, mask = 1U << (2 * (n - 1)); i < mask; i++) {
print_combination(i, values, n);
}
return 0;
}
Voici une version plus élaborée qui traite toutes les permutations de l'ensemble des données :
#include <stdio.h>
#include <stdlib.h>
void print_combination(unsigned mask, int *values, int n) {
int x = values[0];
printf("%d", values[0]);
for (int i = 1; i < n; i++, mask /= 4) {
switch (mask % 4) {
case 0: x += values[i]; printf(" + %d", values[i]); break;
case 1: x -= values[i]; printf(" - %d", values[i]); break;
case 2: x *= values[i]; printf(" * %d", values[i]); break;
case 3: x /= values[i]; printf(" / %d", values[i]); break;
}
}
printf(" = %d\n", x);
}
unsigned print_combinations(int *values, int n) {
unsigned i, mask;
for (i = 0, mask = 1U << (2 * (n - 1)); i < mask; i++) {
print_combination(i, values, n);
}
return mask;
}
unsigned perm(const int *src, int len, int *dest, int *bits, int n) {
if (n == len) {
return print_combinations(dest, len);
} else {
unsigned count = 0;
for (int i = 0; i < len; i++) {
if (bits[i] == 0) {
bits[i] = 1;
dest[n] = src[i];
count += perm(src, len, dest, bits, n + 1);
bits[i] = 0;
}
}
return count;
}
}
int main(int argc, char *argv[]) {
int n = argc - 1;
int values[n], dest[n], bits[n];
for (int i = 0; i < n; i++) {
values[i] = strtol(argv[i + 1], NULL, 0);
bits[i] = 0;
}
printf("%u combinations\n", perm(values, n, dest, bits, 0));
return 0;
}