//bullcow3.c -- How to generate 4 different digits? /* 這也是可以RUN 的程式, by tsaiwn@csie.nctu.edu.tw Demo how to 想出四位不同數字 --- 給 Bulls and Cows GAME 用的) *** *** How to generate four "different" digits? *** Try the following program: ( 可試 gcc -DDEBUG bullcow3.c ) *** --------------------------------------------------*********/ #include #include #include // 以下的 macro 讓程式可以寫成很像 Pascal 語言的 repeat .. until #define repeat do{ #define until(x) }while(!(x)) char myNum[5], yourGuess[5]; //想一想 why 用 5 個 ? char x; int myRandom( ); /* I will write it later on */ int main( ) { int k, seed=0; myNum[4] = 0; /* same as '\0' */ printf("讓我想好四位數字...\r\n"); /****** 去掉這列再 run 看看 ****** // 在這列最左打 // 就可 //以下兩列等於做 randomize 設定亂數種子, 把亂數弄亂 ! seed = (int) time(0) & 0xffff; // 只留下右邊 16 bits srand( seed ); /*** set seed ***/ // 這列不要亂改喔! #ifdef DEBUG printf("seed=%d===\n", seed); // gcc -DDEBUG bullcow3.c #endif myNum[0] = myRandom(); repeat x= myRandom(); until (x != myNum[0]); myNum[1] = x; x= myRandom( ); // 生出新 x while( x== myNum[0] || x == myNum[1]) // 注意條件 x= myRandom( ); myNum[2] = x; repeat x= myRandom( ); until ( (x != myNum[0]) && x!= myNum[1] && x!= myNum[2]); myNum[3] = x; for(k=0; k<=3; k++) myNum[k] += '0'; // convert to ASCII printf("我想好的是: %s\r\n", myNum); // myNum[ ] 當作字串 } int myRandom( ) { int ans= rand( ); // 在 內 return ans % 10; /* 0..9 */ } /*********** Q: 為何此例生出的數字 "總是" 1740 ? (不同電腦系統則可能不同) A: 因為 Pseudo Random 啊! 若要真 random, 可利用 time() 取一值做 rand( ) 的 seed (種子) 在主程式一開始先 叫用 srand( time(0) ); 就會變啦! 注意看程式中那列: " /****** 去掉這列再 run 看看 ****** " see "man 3 rand" 和 "man 3 srand" 以及 "man 3 time" 關於亂數Pseudo Random請用 http://gogle.com 打入 "PRNG wiki" 查詢 **************************************************************/