//cow02.c -- by tsaiwn@csie.nctu.edu.tw //sample to generate ALL possible answers for Bll&Cow game #include int x[5040]; /* 總共 0123 到 9876 四位數不同者有 5040 個 = 10*9*8*7 */ int prepare(); /* 填滿 0123 .. 9876 into x[] */ void next(int); /* 印 "," 或是 "\n" */ /***********/ int main(){ int i, n; static char tmpbuf[99]; /* temporary buffer */ fprintf(stderr, " to generate ALL possible answers for B&C game.\n"); n = prepare(); printf("Total %d numbers found. ", n); printf("The first 80 numbers:\n"); for(i=0; i< 80; i++, next(i)) printf(" %04d", x[i]); printf("\n Hit return to continue..."); fgets(tmpbuf,99, stdin); /* wait a line input */ for(i=80; i< 5040; i++, next(i)) printf(" %4.4d", x[i]); printf("\nBye bye\n"); } void next(int i){ if(i%8) printf(","); else printf("\n"); } int prepare(){ int p=0, i,k,m,n; for(i=0; i<=9; i++){ for(k=0; k<=9; k++){ if(k==i) continue; /* 第二位k與第一位數i相同的都不要 */ for(m=0; m<=9; m++){ if(m==k || m==i) continue; for(n=0; n<=9; n++){ if(n==m || n==k || n==i) continue; x[p++] = i*1000+k*100+m*10+n; } } } } return p; }