game.h
game.c/* * game.h * * Created on: 2011-9-27 * Author: brunie */ #ifndef GAME_H_ #define GAME_H_ #define MAX 13 #define N 4 #define RES 24 #define E (1E-6) #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> typedef struct Node { double res; struct Node *left; struct Node *right; char op; }Node, *pNode; int calculate(Node **list, int n); int operate(double left, double right, double *res, int i, char *op); void print_item(Node *p); int play_game(); #endif /* GAME_H_ */
/* * game.c * * Created on: 2011-9-27 * Author: brunie */ #include "game.h" int num[N] = {8, 10 , 7 , 8}; pNode list[N]; int success = 0; int operate(double left, double right, double *res, int i, char *op) { switch(i) { case 0: *res = left + right; *op = '+'; break; case 1: *res = left - right; *op = '-'; break; case 2: *res = left * right; *op = '*'; break; case 3: if(right == 0) return 0; else *res = left / right; *op = '/'; break; } return 1; } int calculate(Node **list, int n) { int i,j,k,t = 1; if(n == 1) { if(fabs(list[0]->res - RES) < E) { print_item(list[0]); printf("\n"); success = 1; } } else { Node **next = (Node **)malloc((n - 1) * sizeof(pNode)); pNode p = (pNode)malloc(sizeof(Node)); next[0] = p; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (j != i) { for ( k = 0; k < n; k++) { if (k != i && k != j) next[t++] = list[k]; } for ( k = 0; k < 4; k++) { operate(list[i]->res, list[j]->res, &(p->res), k, &(p->op)); p->left = list[i]; p->right = list[j]; calculate(next, n - 1); } } }// for j }// for i }//else return 1; } int priority(char op) #include "game.h" { if (op == 0) return 3; else if (op == '+' || op == '-') return 1; else return 2; } void print_item(Node *p) { if (p->left == 0 && p->right == 0) printf("%d",(int)(p->res)); else { if (priority(p->op) > priority(p->left->op)) { printf("("); print_item(p->left); printf(")"); } else print_item(p->left); printf(" %c ",p->op); if (priority(p->op) > priority(p->right->op)) { printf("("); print_item(p->right); printf(")"); } else print_item(p->right); } } void init() { int i; for (i = 0; i < N; i++) { list[i] = (pNode)malloc(sizeof(Node)); list[i]->left = 0; list[i]->right = 0; list[i]->res = num[i]; list[i]->op = 0; } } int play_game() { init(); calculate(list, N); return success; }
main.c
/* * main.c * * Created on: 2011-9-27 * Author: brunie */ #include "game.h" int main() { setbuf(stdout,0); int status; status = play_game(); if (status) printf("Successful!\n"); else printf("Not exist!\n"); return 0; }