Lua在二维数组中实现左移和右移元素

我有一个2D数组:grid[x][y]

1     2     3     4     5     6     7     8
11    12    13    14    15    16    17    18
21    22    23    24    25    26    27    28
31    32    33    34    35    36    37    38
41    42    43    44    45    46    47    48

示例:我想将第三列向下移动,底部元素进入第一行,如下所示:

41    2     3     4     5     6     7     8
 1    12    13    14    15    16    17    18
11    22    23    24    25    26    27    28
21    32    33    34    35    36    37    38
31    42    43    44    45    46    47    48

我使用了以下函数来左右移动整个数组,但在2D数组中,这显然不起作用,因为如果要移动元素,则必须将其移动到另一个数组中:

function wrap( t, l )
    -- 将i=0更改为向左移动,将i=1更改为向右
    for i = 1, l do
        table.insert( t, 1, table.remove( t, #t ) )
    end
end

我在Lua scratchpad中尝试了这个函数,但它不起作用……我无法找出逻辑,而不失去元素。

function shift( t, direction )

for i=1,#t do
    if(direction == "left") then
            if(i == 1) then
                tempElement = t[#t][6]
            else
                tempElement = t[i-1][6]
            end
    else
            if(i == 7) then
                tempElement = t[1][6]
            else
                tempElement = t[i+1][6]
            end
    end

table.insert( t[i], 6, tempElement )
table.remove( t[i], 12)

end

end

如何将元素移到另一列但是相同的索引,以便grid[5] [1]进入grid[4] [1]等。

点赞
用户869951
用户869951

根据您的评论,您正在尝试在列内移动内容,例如:

{{11,12,13},
 {21,22,23},
 {31,32,33}}

变为

{{31,12,13},
 {11,22,23},
 {21,32,33}}

以下代码使用了您的wrap函数:

g={{11,12,13},{21,22,23},{31,32,33}}

function shifItemWithinRow( array, shift )
    shift = shift or 1 -- make second arg optional, defaults to 1
    for i = 1, shift do
        table.insert( array, 1, table.remove( array, #array ) )
    end
end

function shifItemWithinColumn( grid, columnID, shiftCount )
    shiftCount = shiftCount or 1 -- make second arg optional, defaults to 1

    -- 将所有内容从g复制到新表中,并进行位移:
    local numRows = #grid
    local newCol = {}
    for i=1,numRows do --
         local newI = i+shiftCount
         if newI > numRows then newI = newI - numRows end
         if newI < 1       then newI = numRows - newI end
         newCol[newI] = grid[i][columnID]
    end

    -- 将所有内容复制到网格中
    for i=1,numRows do -- # each row
         grid[i][columnID] = newCol[i]
    end
end

function printGrid(g)
    for i, t in ipairs(g) do
        print('{' .. table.concat(t, ',') .. '}')
    end
end

printGrid(g)
shifItemWithinColumn(g, 1) -- 将第1列向右移动1位
print()
printGrid(g)
print()
shifItemWithinColumn(g, 1, -1)  -- 将第1列向左移动1位
printGrid(g)

此示例将其中一列向右移动1位再向左移动1位(最终结果与开始相同)。

2014-03-28 18:27:52