Search code examples
lua

"Rotating" tables in Lua?


Let's say that I have table X:

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

My goal is to "rotate" X, so that it turns into table Y:

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

I would also prefer if the solution also works for asymmetrical tables, like Z:

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

Please make this work with Vanilla Lua 5.1, no additions.


Solution

  • 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
    

    Example of usage:

    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}
    -- }