我正在制作 java yahtzee 游戏,我只是想知道以下代码在任何情况下是否都会产生误报
die 是一个数组,其中包含每个骰子的伪随机(Math.random())数字,我已使用冒泡排序对它们进行排序 前任: 如果随机抛出骰子,其中 {1,2,1,2,1),则它们将被排序到 {1,1,1,2,2},然后由返回 boolean 值的方法内的以下代码进行检查.
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;
最佳答案
排序和测试比需要的更复杂。它也更慢。试试这个,计算每个数字出现的次数,并检查是否有 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);
请注意,对于所有五个都相同的 Yahtzee,这将返回 false
。如果您希望返回 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);
顺便说一句,你真的不应该对任何事情使用冒泡排序,即使你不会注意到它对于只有五个元素的数组的低效率......
关于java yahtzee 游戏检查满堂彩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26265708/