Lua在二维数组中实现左移和右移元素
2014-3-29 20:6:58
收藏:0
阅读:118
评论:1
我有一个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]等。
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
根据您的评论,您正在尝试在列内移动内容,例如:
变为
以下代码使用了您的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位(最终结果与开始相同)。