通过多维数组

时间:2013-01-17 18:19:53

标签: powershell

我觉得我一直都在讨论这个问题,所以很抱歉'这个家伙'。

我的四连胜游戏现在可以运行,直到需要连续四次检查。 X和O会像魅力一样添加到列中,并且网格显示正确。现在的观点是,我想在多维数组中检查连续四行,但是使用if语句似乎并没有像我一样写给我的方式,因为我必须写这个:

if ($CreateBoard[1,0] -and $CreateBoard[1,1] -and $CreateBoard[1,2] -and $CreateBoard[1,3] -eq "X") {Write-host "Exit script!"}
if ($CreateBoard[1,1] -and $CreateBoard[1,2] -and $CreateBoard[1,3] -and $CreateBoard[1,4] -eq "X") {Write-host "Exit script!"}
if ($CreateBoard[1,2] -and $CreateBoard[1,3] -and $CreateBoard[1,4] -and $CreateBoard[1,5] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,3] -and $CreateBoard[1,4] -and $CreateBoard[1,5] -and $CreateBoard[1,6] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,4] -and $CreateBoard[1,5] -and $CreateBoard[1,6] -and $CreateBoard[1,7] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,5] -and $CreateBoard[1,6] -and $CreateBoard[1,7] -and $CreateBoard[1,8] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,6] -and $CreateBoard[1,7] -and $CreateBoard[1,8] -and $CreateBoard[1,9] -eq "X") {Write-host "Exit script!"}
if ($CreateBoard[1,7] -and $CreateBoard[1,8] -and $CreateBoard[1,9] -and $CreateBoard[1,10] -eq "X") {Write-host "Exit script!"} 

为每一列,然后排,然后走对角线。现在的问题是:有没有快速的方法来通过我的10x10网格(我想使用forach的Foreach-Object?),如果是的话,你能提供一个基本的例子吗? (如果重要的话,我试图找到连续4次字符串“X”或“O”)

由于

1 个答案:

答案 0 :(得分:1)

这是一个算法问题,而不是PowerShell问题。 :-)也就是说,一个简单的方法是这样的:

function FindFourInARow($brd, $startRow, $startCol)
{
    $numRows = $brd.GetLength(0);
    $numCols = $brd.GetLength(0);

    #search horizontal
    $found = 0;
    $cnt  = 0;
    for ($col = $startCol; $col -lt $numCols -and $cnt -lt 4; $col++, $cnt++)
    {
        if ($brd[$startRow, $col] -eq 'X')
        {
            $found += 1
            if ($found -eq 4) { return $true }
        }
    }

    #search vertical
    $found = 0;
    $cnt = 0;
    for ($row = $startRow; $row -lt $numRows -and $cnt -lt 4; $row++, $cnt++)
    {
        if ($brd[$row, $startCol] -eq 'X')
        {
            $found += 1
            if ($found -eq 4) { return $true }
        }
    }

    #search diag forwards
    $found = 0;
    $row = $startRow
    $col = $startCol
    $cnt = 0;
    for (;$row -lt $numRows -and $col -lt $numCols -and $cnt -lt 4; 
          $row++, $col++, $cnt++)
    {
        if ($brd[$row, $col] -eq 'X')
        {
            $found += 1
            if ($found -eq 4) { return $true }
        }
    }

    return $false
}

# TODO: implement search diag backwards

$brd = New-Object 'char[,]' 10,10
$brd[2,2] = $brd[3,3] = $brd[4,4] = $brd[5,5] = 'X'

$numRows = 10
$numCols = 10
for ($r = 0; $r -lt ($numRows - 3); $r++)
{
    for ($c = 0; $c -lt ($numCols - 3); $c++)
    {
        if (FindFourInARow $brd $r $c)
        {
            "Found four in a row at $r,$c"
            $r = $numRows
            break;
        }
    }
}

我直接在SO中输入了这个。它可能会有一些错误,但它应该给你基本的要点。