javascript 在动态大小的2D数组中搜索正梯度

hmae6n7t  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(69)

例如,我需要在一个二维数组中搜索一个正负梯度值。
正梯度:左下〉中间〉右上
负梯度:左上〉中间〉右下

[
    ['x',  'x',  'o'],
    [null, null, 'o'],
    ['x', 'x',   null] 
]

我有两个函数。首先在for循环中找到值,当找到值时,这两个函数都运行以搜索迷宫的正梯度和负梯度,如果找到获胜的组合,则返回true。
scanfornegativegradientcombinations工作,scanForPositiveGradientCombinations不工作,并以typeError结束。我认为问题可能是在减少rowIndex时,我正在将游戏推出界限,但我不确定。

const isDiagonalWinner = (rowCellValues, winCountCondition, player) => {

for(let rowIndex = 0; rowIndex < rowCellValues.length; rowIndex++){
    for(let columnIndex = 0; columnIndex < rowCellValues[rowIndex].length; columnIndex++){
        const cellValue = rowCellValues[rowIndex][columnIndex];
        if(cellValue === player.symbol) {
            console.log('initiating player scan for ', player.symbol, 'at', [rowIndex, columnIndex]);
            if(scanForNegativeGradientCombinations(columnIndex, rowIndex, rowCellValues, player.symbol, winCountCondition)) {
                return true
            } 

            if(scanForPositiveGradientCombinations(columnIndex, rowIndex, rowCellValues, player.symbol, winCountCondition)) {
                return true
            }
        }
    }
}

return null;
};

以上是将调用以下2个函数的函数。

const scanForNegativeGradientCombinations= (columnIndex, rowIndex, rowCellValues, playerSymbol, winCountCondition) => {
let counter = 0;
while(rowIndex < rowCellValues.length && columnIndex < rowCellValues[rowIndex].length){
    if(rowCellValues[rowIndex][columnIndex] === playerSymbol){
        counter++;
    }
    if(counter >= winCountCondition){
        return true;
    }
    rowIndex++;
    columnIndex++;
}
return false;
}

const scanForPositiveGradientCombinations= (columnIndex, rowIndex, rowCellValues, playerSymbol, winCountCondition) => {
let counter = 0;
while(rowIndex < rowCellValues.length && columnIndex < rowCellValues[rowIndex].length){
    if(rowCellValues[rowIndex][columnIndex] === playerSymbol){
        counter++;
    }
    if(counter >= winCountCondition){
        return true;
    }
    rowIndex--;
    columnIndex++;
}
return false;
}
wbrvyc0a

wbrvyc0a1#

function sequence(n) { return Array(n).fill().map((_,i)=>i) }

function diagonalWin(board) {
  let d = board.length
  let seq = sequence(d)
  return board[0][0]!==null && seq.every(i=>board[i][i]===board[0][0]) ||
  board[0][d-1]!==null && seq.every(i=>board[i][d-i-1]===board[0][d-1])
}

console.log(diagonalWin([
  ['x',  'x',  'o'],
  [null, null, 'o'],
  ['x', 'x',   null]
]))

console.log(diagonalWin([
  ['x',  'x',  'o'],
  [null, 'x', 'o'],
  ['x', 'x',  'x']
]))

console.log(diagonalWin([
  ['x',  'x',  'o'],
  [null, 'o', 'o'],
  ['o', 'x',  'x']
]))

相关问题