Lua的“旋转”桌子?

时间:2017-09-29 15:51:19

标签: lua

假设我有表X:

{
  {1,1,1},
  {1,0,0},
  {1,1,1}
}

我的目标是“旋转”X,使其变为表Y:

{
  {1,1,1},
  {1,0,1},
  {1,0,1}
}

如果解决方案也适用于非对称表格,我也更喜欢,例如Z:

{
  {1,1,1},
  {1,0,0},
  {1,1,1},
  {1,1,0}
}

请使用Vanilla Lua 5.1,无需添加。

2 个答案:

答案 0 :(得分:0)

function transpose(m)
   local rotated = {}
   for c, m_1_c in ipairs(m[1]) do
      local col = {m_1_c}
      for r = 2, #m do
         col[r] = m[r][c]
      end
      table.insert(rotated, col)
   end
   return rotated
end

function rotate_CCW_90(m)
   local rotated = {}
   for c, m_1_c in ipairs(m[1]) do
      local col = {m_1_c}
      for r = 2, #m do
         col[r] = m[r][c]
      end
      table.insert(rotated, 1, col)
   end
   return rotated
end

function rotate_180(m)
   return rotate_CCW_90(rotate_CCW_90(m))
end

function rotate_CW_90(m)
   return rotate_CCW_90(rotate_CCW_90(rotate_CCW_90(m)))
end

使用示例:

local m1 = {
  {1,1,1},
  {1,0,0},
  {1,1,1},
  {1,1,0}
}

local m2 = rotate_CCW_90(m1)
-- m2 now is {
--    {1, 0, 1, 0},
--    {1, 0, 1, 1},
--    {1, 1, 1, 1}
-- }

local m3 = transpose(m1)
-- m3 now is {
--    {1, 1, 1, 1},
--    {1, 0, 1, 1},
--    {1, 0, 1, 0}
-- }

答案 1 :(得分:0)

你想要转发:

function transponieren (udata)
    local tdata = {}
    for y, xs in pairs (udata) do
        for x, value in pairs (xs) do
            tdata[x]=tdata[x]or{}
            tdata[x][y]=value
        end
    end
    return tdata
end

local udata = {
    {  1,   0, 0.9},
    {0.9, 0.5,   1},
    {  0, 0.1,   1},
}
udata = transponieren (udata) -- transponiered