24 시 게임 의 프로 그래 밍 알고리즘 (C 언어 구현)

#include <stdio.h>
#include <string.h>
#include <math.h>

#define LING	1E-6
#define CONT	4
#define VOLUE	24

float number[CONT];		
char expression[CONT][20] ;				
bool m_judge = false; 							//      。
int count = 0;

void Find(int n)
{
	int i = 0, j = 0;

	if (n == 1)
	{
		if ( fabs(number[0] - 24) <= LING)
		{
			for (i = 0; i < 20; i++) 
			{
				printf("%c", expression[0][i]) ;
			}
			printf("\t\t") ;
			m_judge = true;
			count ++;
			if((count % 2)==0) 				//           
				printf("
") ; } else { } } for(i = 0; i < n; i++) // { for (j = i + 1; j < n; j++) // { float a, b; char expressiona[20], expressionb[20]; a = number[i] ; b = number[j] ; number[j] = number[n - 1]; strcpy(expressiona, expression[i]) ; strcpy(expressionb, expression[j]) ; strcpy(expression[j], expression[n - 1]) ; sprintf(expression[i], "(%s+%s)", expressiona, expressionb) ; number[i] = a + b; Find(n-1); /////////////////////////////////// sprintf(expression[i], "(%s-%s)", expressiona, expressionb) ; number[i] = a - b; Find(n-1); sprintf(expression[i], "(%s-%s)", expressionb, expressiona) ; number[i] = b - a; Find(n-1); sprintf(expression[i], "(%s*%s)", expressiona, expressionb) ; number[i] = a * b; Find(n-1); if (b != 0) { sprintf(expression[i], "(%s/%s)", expressiona, expressionb) ; number[i] = a / b; Find(n-1); } if (a != 0) { sprintf(expression[i], "(%s/%s)", expressionb, expressiona) ; number[i] = b / a; Find(n-1); } number[i] = a; // Find(2) a number[i] number[0] number[j] = b; // Find(2) b nubmer[j] number[1] strcpy(expression[i], expressiona) ; strcpy(expression[j], expressionb) ; } } } int main() { int i, j ; printf(" :
") ; for (i = 0; i < CONT; i++) { char ch[20], s; int a ; printf(" %d :", i+1) ; scanf("%f", &number[i]) ; a = (int)number[i] ; s = char(a + 48); ch[0] = s ; for (j = 1; j < 20; j++) { ch[j] = 0 ; } strcpy(expression[i], ch) ; } printf("
") ; Find(CONT) ; if(m_judge==true) { printf("

!
") ; printf(" :%d
", count) ; } else { printf(" !") ; } return 0; }

좋은 웹페이지 즐겨찾기