Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <cs50.h>
- #include <string.h>
- #include <ctype.h>
- // number of tabs with numbers
- #define NBTAB 6
- // number of operations (+-*/)
- #define NBOP 4
- #define DIFF(a, b) (((a) > (b))? ((a) - (b)):((b) - (a)))
- // I need to printf in my string the complete operation to keep track of it, to prinf it later in main
- #define SPRINT_OP(a, b, ope, result) {strcmp(tmp_res, res); sprintf(res,"%d %c %d = %d\n%s",(((a)>(b))?(a):(b)),c_op[ope],(((a)>(b))?(b):(a)),result,tmp_res);}
- int best = 0;
- int best_diff = 999;
- char res[255];
- char tmp_res[255];
- int add(int *a, int b)
- {
- return(*a += b);
- }
- int sub(int *a, int b)
- {
- return(*a = DIFF(*a, b));
- }
- int mult(int *a, int b)
- {
- return(*a *= b);
- }
- int divi(int *a, int b)
- {
- if( *a > b )
- {
- if(((*a && b) != 0) && (b != 1) && ((*a % b) == 0))
- return(*a = *a / b);
- }
- if( b > *a)
- {
- if(((*a && b) != 0) && (*a != 1) && ((b % *a) == 0))
- return(*a = b / *a);
- }
- return 0;
- }
- // now I need an array of if int containing all the possible operations
- int(*op[])(int* ,int) = {add, sub, mult, divi};
- // now I need an array of char for the 4 operators
- char c_op[] ="+-*/";
- int compute(int* tab, int nb, int total)
- {
- int i, j, k; // counters!!
- int t[NBTAB]; // array of int of length the number "given" on the tabs
- // now i will go from 0 to n-1 and j from i+1 to n, regular search nested for loops
- for(i = 0; i < (nb - 1); i++)
- {
- for(j = (i + 1); j < nb; j++)
- {
- // k is the inner loop, for each i and j, we do the 4 op aka NBOP
- for(k = 0; k < NBOP; k++)
- {
- memcpy(t, tab, sizeof(int) * NBTAB); // pointers yay!!
- if((*op[k])(&t[i], t[j]))
- {
- if(t[i] == total)
- return(SPRINT_OP(tab[i], tab[j], k, t[i]));
- if(DIFF(t[i], total) < best_diff)
- {
- best = t[i];
- best_diff = DIFF(best, total);
- }
- t[j] = t[nb - 1];
- if(compute(tab, nb - 1, total))
- return(SPRINT_OP(tab[i], tab[j], k, t[i]));
- }
- }
- }
- }
- return 0;
- }
- int main (void)
- {
- //res = {NULL};
- int i, num, total = 0, t[NBTAB];
- int draw[] = {1,2,3,4,5,6,7,8,9,10,25,50,75,100};
- for (i = 0; i < NBTAB; i++)
- {
- num = draw[rand() % 14];
- printf("number %d : %d\n",(i+1), num);
- t[i] = num;
- }
- total = (100+(rand() % 899));
- printf("total: %d\n", total);
- if(!compute(t, NBTAB, total))
- (compute(t, NBTAB, best));
- else
- printf("We have an answer!\n");
- //printf("%s",res);
- return (!printf(res));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement