From eeb456d954b90c8f1c9247d91afde52d690778ff Mon Sep 17 00:00:00 2001 From: olivier gayot Date: Thu, 13 Dec 2012 11:54:29 +0000 Subject: le_compte_est_bon: make the solver work with any number of arguments --- main.c | 26 ++++++++++++++------------ solver.c | 18 +++++++++++------- 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/main.c b/main.c index 4a8fd98..a366ec9 100644 --- a/main.c +++ b/main.c @@ -4,23 +4,25 @@ int main(int argc, char **argv) { + const char *arg0 = *argv++; vect_t vect; - if (argc != 8) { - puts("takes exactly 7 args"); - return -1; + if (argc < 3) + goto usage; + + vect.len = argc - 2; + vect.array = malloc(sizeof(int) * vect.len); + + for (int i = 0; i < (signed)vect.len; ++i) { + vect.array[i] = atoi(*argv++); } - vect.array = malloc(sizeof(int) * 6); - vect.array[0] = atoi(argv[1]); - vect.array[1] = atoi(argv[2]); - vect.array[2] = atoi(argv[3]); - vect.array[3] = atoi(argv[4]); - vect.array[4] = atoi(argv[5]); - vect.array[5] = atoi(argv[6]); - vect.len = 6; - solve(&vect, atoi(argv[7])); + solve(&vect, atoi(*argv)); free(vect.array); return 0; + +usage: + fprintf(stderr, "Usage: %s number ... result\n", arg0); + return -1; } diff --git a/solver.c b/solver.c index 334848e..27de4ca 100644 --- a/solver.c +++ b/solver.c @@ -12,10 +12,10 @@ typedef uint8_t byte; enum { - addition, - substraction, - multiplication, - division, + addition , + substraction , + multiplication , + division , }; typedef struct { @@ -30,6 +30,7 @@ typedef struct { } solution_t; static solution_t solution_g; +static vect_t *vect_g; static int result; static int closer = -1; @@ -38,10 +39,9 @@ static int closer = -1; static void display_solution(void) { - puts("--------------------------"); puts("found a (better) solution:"); - for (int i = 5; i >= solution_g.level; i--) { + for (int i = vect_g->len - 1; i >= solution_g.level; i--) { char op; int _result; @@ -72,6 +72,7 @@ static void display_solution(void) , solution_g.computation[i].v2 , _result); } + puts("--------------------------"); } /* }}} */ @@ -161,13 +162,16 @@ static void solve_rec(vect_t *vect) /* public function to use */ void solve(vect_t *vect, int _result) { + vect_g = vect; result = _result; solution_g.computation = malloc(sizeof(computation_t) * vect->len); solution_g.level = 0; solve_rec(vect); - if (closer != result) { + if (closer == result) { + puts("Le compte est bon!"); + } else { result = closer; closer = -1; solve_rec(vect); -- cgit v1.2.3