2014-10-08 44 views
0

我想提出的Java的Yahtzee比賽,我只是想知道如果下面的代碼會產生假陽性在任何情況下的Java的Yahtzee遊戲支票滿堂紅

模具是一種含有僞隨機數組(的Math.random( ))每個模具的數字,我已經使用冒泡排序 ex: 如果隨機拋出die {1,2,1,2,1}他們然後將排序到{1,1,1,2, 2},然後由以下代碼檢查,該代碼位於返回布爾值的方法內。

int count = 0; 
if(die[0] == die[1] && die[1] == die[2] || die[0] == die[1] && die[2] != die[1]){ 
    count++; 
} 
    if(die[3] == die[4]){ 
     count++; 
    } 
    if(count > 1){ 
     return true; 
    } 
    return false; 
+0

排序將使檢查各種檢查變得容易。 5個骰子沒有實際的複雜性問題,而是使用插入排序。排序後,循環並重復計數。 – auval 2014-10-08 21:07:29

回答

0

你會檢查有多少數字都在那裏,所以你的基礎算法中是這樣,那麼:

int[] amount = { 0, 0, 0, 0, 0, 0 } 

for(int i = 0; i < dices.length; i++) { // dices is your integer array 
    switch(dices[i]) { 
     case 1: amount[1] += 1; break; 
     // all other cases up to 6 
    } 
} 

// from the amount array you can check for other things too, here it is for the full house: 
boolean got3same = false; 
boolean got2same = false; 
for(int i = 0; i < amount.ength && (!got3same || !got2same); i++) { 
     if(!got3same && amount[i] == 3) { 
      got3same = true; 
     } else if(!got2same && amount[i] == 2) { 
      got2same = true; 
     } 
    } 

    if(got3same && got2same) { 
     System.out.println("Full House!"); 
    } 
+0

正確的想法,但有很多事情可以改進:你不需要用零初始化一個數組;你不需要'switch'語句,但可以使用'amount [dices [i] -1] ++';每次檢查'(!got3same ||!got2same)'都會更快。 – 2014-10-08 20:55:42

0

這複雜得多,它需要進行排序,然後測試。它也比較慢。試試這個,計算每個數字出現的次數,並檢查你是否有3和2.你不需要先排序數組。

int[] counts = new int[6]; 
for (int i=0; i<die.length; i++) 
    //increase the relevant counter 
    counts[die[i]-1]++; 
//now check we've got a 2 and a 3 
boolean check2 = false; 
boolean check3 = false; 
for (int i: counts) { 
    check2 |= (i==2); //found 2 of some number 
    check3 |= (i==3); //found 3 of some number 
} 
return (check2 && check3); 

注意這將返回false的Yahtzee的所有五個是一樣的。如果你想要返回true,那麼添加check5就足夠簡單了。 (實際上它應該回到true,因爲它允許以計數的Yahtzee作爲一個完整的家,如果你想。),那麼它將成爲:

int[] counts = new int[6]; 
for (int i=0; i<die.length; i++) 
    //increase the relevant counter 
    counts[die[i]-1]++; 
//now check we've got a 2 and a 3 
boolean check2 = false; 
boolean check3 = false; 
for (int i: counts) { 
    check2 |= (i==2); //found 2 of some number 
    check3 |= (i==3); //found 3 of some number 
    if (i==5) return true; //found a Yahtzee so stop and return true 
} 
return (check2 && check3); 

通過,你真的不應該永遠使用冒泡排序的方式對於任何事情來說,即使你不會注意到其中只有五個元素的陣列效率低下......