赢得第3场比赛的条件

时间:2011-01-10 22:40:16

标签: c++

我有一个随机生成的10x5数组,当3个数字水平和垂直匹配时,我想检查它。我无法弄清楚检查数字是否匹配的好方法。我目前正在这样做的方式,我需要70多个if语句,而且我知道有更好的方法。我不认为我可以使用for循环检查,因为我需要确切地知道哪3个数字(和它们的位置)是相同的。

这是我到目前为止的代码,对不起,如果它有点长。我只包括一行检查以节省空间。


#include <iostream>
#include <time.h>
#include <cstdlib>
#include <cstdio>

using namespace std;
int col = 5;
int row = 0;

int board[9][4];
int i;

int main(int argc, char * argv[])
{
 srand(time(NULL));

 // generate the random board

 cout << "==========\n";
 while (row < 1)
 {
  for(i = 0; i < 5; i++)
  {
   board[row][i] = rand()%5 + 1;
   cout << board[row][i] << " ";
  }
  cout << endl;
  cout << "==========\n";
  row++;
 }

 //----check for matches-----

 // row 1
 if (board[0][0] == (board[0][1] && board[0][2]))
 {
  cout << "Balls 1,2,3 match\n";
 }
 if (board[0][2] == (board[0][3] && board[0][4]))
 {
  cout << "Balls 3,4,5 match\n";
 }
 if (board[0][1] == (board[0][2] && board[0][3]))
 {
  cout << "Balls 2,3,4 match\n";
 }
 if (board[0][0] == (board[0][1] && board[0][2] && board[0][3]))
 {
  cout << "Balls 1,2,3,4 match\n";
 }
 if (board[0][1] == (board[0][2] && board[0][3] && board[0][4]))
 {
  cout << "Balls 2,3,4,5 match\n";
 }
 if (board[0][0] == (board[0][1] && board[0][2] && board[0][3] && board[0][4]))
 {
  cout << "Balls 1,2,3,4,5 match\n";
 }
 else
 {
  cout << "No balls match\n";
 }

 return 0;
}

1 个答案:

答案 0 :(得分:0)

我在这个问题与您之前的问题之间看到的唯一区别是您想知道比赛的位置和方向。在这种情况下,这是对@ templatetypedef的function的一个小修改。

enum Direction { NONE, VERTICAL, HORIZONTAL, DIAGONAL_UP, DIAGONAL_DOWN };

Direction IsLineStartingAt(int x, int y) {
    if (IsLinearMatch(x, y, 1,  0) return HORIZONTAL;
    if (IsLinearMatch(x, y, 0,  1) return VERTICAL;
    if (IsLinearMatch(x, y, 1,  1) return DIAGONAL_DOWN;
    if (IsLinearMatch(x, y, 1, -1) return DIAGONAL_UP;
    return NONE;
}

如果你通过for循环运行它,你已经有了x和y的起始位置,这将返回方向,如果没有匹配则没有。