C++ 赢得第三场比赛的条件
我有一个随机生成的10x5数组,我想在3个数字水平和垂直匹配时检查它。我想不出一个好办法来检查数字是否匹配。按照我目前的做法,我需要70多条if语句,我知道还有更好的方法。我不认为我可以使用for循环来检查,因为我需要确切地知道哪3个数字和它们的位置是相同的 这是我到目前为止的代码,如果它有点长,很抱歉。为了节省空间,我只包含了一行的检查C++ 赢得第三场比赛的条件,c++,C++,我有一个随机生成的10x5数组,我想在3个数字水平和垂直匹配时检查它。我想不出一个好办法来检查数字是否匹配。按照我目前的做法,我需要70多条if语句,我知道还有更好的方法。我不认为我可以使用for循环来检查,因为我需要确切地知道哪3个数字和它们的位置是相同的 这是我到目前为止的代码,如果它有点长,很抱歉。为了节省空间,我只包含了一行的检查 #include <iostream> #include <time.h> #include <cstdlib> #include
#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;
}
我认为这个问题和你之前的问题唯一的区别就是你想知道比赛的位置和方向。在这种情况下,这里是对@templatetypedef的一个小修改
如果你通过一个for循环运行,你已经有了x和y的起始位置,这将返回方向,或者如果没有匹配,则没有返回方向。这也是我的文章的可能重复,但这不是同一个问题。这个问题有什么不同?基本思想似乎是一样的,使用一个循环或一系列循环替换无数手写支票。前三个检查是相同的,只是在某些值上加了1。将这些值转换为变量,并编写一个循环,使其运行多次。运行时,代码会做什么?我遗漏了一些关于你使用&&。。。是吗?我需要知道每个匹配的确切位置,而不仅仅是它们是垂直的还是水平的。这些信息可以根据位置和方向导出。如果是水平的,则匹配为[x][y],[x+1][y],[x+2][y],如果是垂直的,则匹配为[x][y],[x][y+1],[x][y+2],等等。。。
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;
}