Skip to content

Instantly share code, notes, and snippets.

@kenornotes
Created January 14, 2015 13:20
Show Gist options
  • Save kenornotes/167042c7f5952c2c4424 to your computer and use it in GitHub Desktop.
Save kenornotes/167042c7f5952c2c4424 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void getRandNum(int ans[]) {
// 洗牌取亂數
// 準備好 pool 陣列,把0~9依序放入
int pool[10], i;
for(i = 0; i <= 9; i++)
pool[i] = i;
// 初始化亂數種子
srand(time(NULL));
// 將 pool 的順序打亂
for(i = 0; i < 10; i++) {
// 隨機取得 0~9 中其中一個數
int randnum = rand()%9;
// 將第 i 位置與第 randnum 位置的值交換
int temp = pool[i];
pool[i] = pool[randnum];
pool[randnum] = temp;
}
// 取打亂後的 pool 的前四個放入 ans[]
for(i = 0; i < 4; i++) {
ans[i] = pool[i];
}
}
int main() {
// a, b 為幾A幾B的係數;guest, ans 為猜的數字與答案的數字;
int a = 0, b,guess[4], ans[4], i, j;
// 產生0~9中隨機不重複的四個數字
getRandNum(ans);
// 輸出答案(測試用)
printf("%d %d %d %d\n", ans[0], ans[1], ans[2], ans[3]);
// 一直給使用者猜,猜到全對為止
while(a != 4) {
// 初始化 A, B 的係數
a = b = 0;
// 開始猜
for(i = 0; i < 4; i++) {
// 輸入數字
scanf("%d", &guess[i]);
// 檢查幾A幾B
for(j = 0; j < 4; j++) {
// 若值是對的,位置相同則 A+1,位置不同則 B+1
if(guess[i] == ans[j]) {
if(i == j) a++;
else b++;
}
}
}
// 輸出結果
printf("%dA%dB\n", a, b);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment