我为我的C ++类编写了这个函数,我尝试了x< = 4并且尝试了x> = 4,但是当我对它进行跟踪时,我并没有看到它像它应该循环。它的作用是取一个由5个数字组成的数组并对它们进行排序,然后检查这个组合是否构成了一个完整的数字。
bool isFullHouse(int)
{
int match = 0;
BubbleSort(DiceHeld, 5);
for ( int x=0; x <= 4; x++ )
{
if (((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+2) && (DiceHeld[4] == x+2) && (DiceHeld[5] == x+2)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+2) && (DiceHeld[5] == x+2)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+3) && (DiceHeld[4] == x+3) && (DiceHeld[5] == x+3)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+3) && (DiceHeld[5] == x+3)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+4) && (DiceHeld[4] == x+4) && (DiceHeld[5] == x+4)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+4) && (DiceHeld[5] == x+4)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+5) && (DiceHeld[4] == x+5) && (DiceHeld[5] == x+5)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+6) && (DiceHeld[4] == x+2) && (DiceHeld[5] == x+2)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+6) && (DiceHeld[4] == x+6) && (DiceHeld[5] == x+6)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+6) && (DiceHeld[5] == x+6)))
{
match = 1;
}
}
if (match == 1)
{
return true;
}
else
{
return false;
}
}
答案 0 :(得分:1)
DiceHeld
的索引应该从0到4运行。根据您的编译器和调试器,内存错误可能不明显,但仍然存在。
我还打赌退出循环后match
不是1。
答案 1 :(得分:1)
为了好玩,这里的版本不需要如此重要的逻辑或排序:
static const int kNumDice = 5;
bool isFullHouse()
{
// There are only 2 possible patterns for full house on a set of numbers, sorted or not
// Either the first 3 dice have the same value and the 4th and 5th dice are the same
// or the first 2 dice match and the 3rd, 4th, 5th dice match
int currentMatch = DiceHeld[0];
int uniqueValues = 1;
int matchLength = 1;
for(int i=1; i<kNumDice; i++)
{
// Start next match
if(DiceHeld[i] != currentMatch)
{
if(matchLength < 2)
{
return false;
}
if(++uniqueValues > 2)
{
return false;
}
currentMatch = DiceHeld[i];
matchLength = 1;
}
else if(++matchLength > 3)
{
return false;
}
}
return true;
}