java - 如果一个元素后面跟着相同的元素n次,如何检查二维数组
问题描述
我正在为模仿井字游戏板的 CS 课程创建这个项目。它适用于原始的 3x3 正方形,但现在我需要让程序询问用户他们想要多大的板。它的大小只能是 3x3 到 14x14 的正方形。我还问他们想要赢得比赛的连续多少个连接或多少个 X 或 O。连接数只能等于或小于大小,但不能小于 3。
对于连续检查水平 x 或 o 的条件最初看起来像这样,
for(int r = 0; r < 3; r++) {
for(int c = 0; c < 1; c++) {
if(board[r][c] == Cell.X && board[r][c + 1] == Cell.X && board[r][c + 2] == Cell.X) {
return GameStatus.X_WON;
}
else if(board[r][c] == Cell.O && board[r][c + 1] == Cell.O && board[r][c + 2] == Cell.O) {
return GameStatus.O_WON;
}
}
}
我已经让程序为连接和电路板尺寸输入输入,称为,
int connections;
SuperTicTacToe.getSize();
我写了这个,
private GameStatus isWinner() {
int count = 0;
for(int r = 0; r < SuperTicTacToe.getSize(); r++) {
for(int c = 0; c < 1; c++) {
for(int i = 0; i < connections; i++){
if(board[r][c + i] == Cell.X ){
count++;
}
if(count == connections){
return GameStatus.X_WON;
}
}
}
}
}
但我似乎唯一不能做的就是让程序以某种方式检查连续存在x或o的连接数。它似乎只检查板上是否有 x 的连接数,而不是在最后一列中计算任何内容。
有没有办法检查一个元素是否等于它前面的相同元素n次?
解决方案
在写下代码之前,画出你作为一个人用来解决这个问题的方法总是好的。如果你曾经在课堂上学过代码,你就会知道白板的重要性。
// This program pretends board is a boolean[][] array
boolean horizontalFlag = true; // Assume that it is a 3 in a row
boolean verticalFlag = true; // If it is proven not to be, then change to false
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
if(!(board[i][j])) verticalFlag = false; // These methods draw horizontal and vertical lines
if(!(board[j][i])) horizontalFlag = false; //i.e.
}
}
/* What the code does, visualized.
Horizontal check = h vertical check = v both = b none = 0
This is based on each iteration of i.
i=0 i=1 i=2
b h h|0 v 0|0 0 v
v 0 0|h b h|0 0 v
v 0 0|0 v 0|h h b
*/
if(board[1][1]) { // Diagonals
if(board[0][0] && board[2][2]) return true;
if(board[2][0] && board[0][2]) return true;
}
if(horizontalFlag||verticalFlag) return true; // If the flags "say" that there are straight lines
请注意,此代码与您的程序不直接兼容。
推荐阅读
- ios - iOS 14 链接模块标志“矮人版本”:ID 具有冲突行为
- php - mysql:加入另一个表并获取最新行
- javascript - 在赛普拉斯配置中存储正则表达式值
- laravel - 不将数据传递到刀片文件
- nestjs - 如何将配置服务值传递给 Nestjs 中的 TypeOrmModule 配置
- google-cloud-platform - 将 sonarqube 与 cloudbuild 集成
- vb.net - 使用 VB.net 监控远程 FTP 服务器
- asp.net - 如何为 ASP.NET 实现 GoJS 组织结构图编辑器?
- php - 以编程方式为每个租户(客户)创建自定义电子邮件收件箱
- apache-spark - Apache Spark 驱动程序、应用程序和计算资源