Five Fours

2012. 6. 8. 14:50 프로그래밍

문득 생각이 나서, 지난 번에 JavaScript로 만든 걸 c로 만들었다

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

#define TABLE_SIZE 256

struct {
	int count;
	struct pair {
		float key;
		char val[32];
	} elements[TABLE_SIZE];
} tables[5];

void addElement(int tableIndex, float key, char *val) {
	int i;
	for (i = 0; i < tables[tableIndex].count; i++)
		if (tables[tableIndex].elements[i].key == key)
			break;
	if (i >= tables[tableIndex].count) {
		if (i >= TABLE_SIZE) {
			fprintf(stderr, "Table[%d] overflow: %d", tableIndex, TABLE_SIZE);
			exit(-1);
		}
		tables[tableIndex].count++;
	}
	tables[tableIndex].elements[i].key = key;
	strcpy(tables[tableIndex].elements[i].val, val);
}

char *getValueFromKey(int tableIndex, float key) {
	int i;
	for (i = 0; i < tables[tableIndex].count; i++)
		if (tables[tableIndex].elements[i].key == key)
			return tables[tableIndex].elements[i].val;
	return NULL;
}

main() {
	int i, j, m, n;
	char buf[32];
	
	for (i = 0; i < 5; i++)
		tables[i].count = 0;
		
	addElement(0, 4, "4");

	for (n = 2; n <= 5; n++)
		for (m = 1; m < n; m++)
			for (i = 0; i < tables[m-1].count; i++)
				for (j = 0; j < tables[n-m-1].count; j++) {
					struct pair e1 = tables[m-1].elements[i],
								e2 = tables[n-m-1].elements[j];
					sprintf(buf, "(%s + %s)", e1.val, e2.val);
					addElement(n-1, e1.key + e2.key, buf);
					sprintf(buf, "(%s - %s)", e1.val, e2.val);
					addElement(n-1, e1.key - e2.key, buf);
					sprintf(buf, "(%s * %s)", e1.val, e2.val);
					addElement(n-1, e1.key * e2.key, buf);
					sprintf(buf, "(%s / %s)", e1.val, e2.val);
					addElement(n-1, e1.key / e2.key, buf);
				}

//	for (i = 0; i < 5; i++)
//		printf("tables[%d].count = %d\n", i, tables[i].count);

	for (i = 0; i <= 20; i++)
		printf("%2d = %s\n", i, getValueFromKey(4, i));
}


Posted by dEtH :