java yahtzee游戏全场检查
我正在制作java yahtzee游戏,我只是想知道下面的代码在任何情况下是否会产生误报 die是一个数组,包含每个die的伪随机(Math.random())数,我使用冒泡排序对它们进行排序 前任: 如果在{1,2,1,2,1)处随机抛出骰子,则它们将被排序为{1,1,1,2,2},然后由以下代码进行检查,该代码位于返回布尔值的方法内java yahtzee游戏全场检查,java,Java,我正在制作java yahtzee游戏,我只是想知道下面的代码在任何情况下是否会产生误报 die是一个数组,包含每个die的伪随机(Math.random())数,我使用冒泡排序对它们进行排序 前任: 如果在{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[
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;
如果您想检查代码的正确性,我建议您进行单元测试(例如使用Junit)。 尝试测试尽可能多的案例,使用参数化测试可能会有所帮助。
请参阅:您将检查有多少个数字,因此您的基本算法如下所示:
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!");
}
int[]amount={0,0,0,0,0}
对于(inti=0;i
排序和测试要比需要的复杂得多。速度也较慢。试试这个,计算每个数字出现的次数,并检查是否有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);
顺便说一句,你真的不应该对任何事情使用冒泡排序,即使你不会注意到它在只有五个元素的数组中的低效…正确的想法,但是有很多事情可以改进:你不需要用零初始化数组;你不需要
switch
语句,但是可以必须使用amount[dices[i]-1]++
;不要每次都检查(!got3same | | |!got2same)
。排序可以轻松检查各种检查。5个骰子没有实际的复杂性问题,但使用插入排序。排序后,只需循环并计算重复次数。
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);