arrays - 如何在 Lua 中使用 For 循环创建自适应反转数组?
问题描述
我需要帮助来使用 for 循环为我的作业创建这个适应性强的反向数组
function for_loop2(a,b)
local out = {}
-- a is the starting number in the array
-- b is the length of the array
--Put your code between here ****************
--and here **********************************
return out
end
is( for_loop2(4,4), {4,3,2,1}, 'For loop adaptable reversed array creation')
is( for_loop2(9,9), {9,8,7,6,5,4,3,2,1}, 'For loop adaptable reversed array creation')
is( for_loop2(4,9), {4,3,2,1,0,-1,-2,-3,-4}, 'For loop adaptable reversed array creation')
report()
除了https://www.lua.org/pil/contents.html之外,我可以参考的任何材料都将不胜感激, 因为我需要更多示例来理解这些概念。
解决方案
function for_loop2( a, b )
local out = {}
-- Start from 4, end at a - b + 1, decrement i by 1
for i = a, a - b + 1, -1 do
out[#out + 1] = i
end
return out
end
is( for_loop2(4,4), {4,3,2,1}, 'For loop adaptable reversed array creation')
is( for_loop2(9,9), {9,8,7,6,5,4,3,2,1}, 'For loop adaptable reversed array creation')
is( for_loop2(4,9), {4,3,2,1,0,-1,-2,-3,-4}, 'For loop adaptable reversed array creation')
report()
在提出的解决方案中,i
不仅是迭代器,而且是新表元素的值。这就是为什么它从 开始a
,结束于a - b + 1
——这是所需表的最后一个元素元素的值,因为我们只需要b
元素,然后向后(-1
增量)。
或者,您可以执行以下操作:
for i = 1, b do -- the default increment is 1.
out[i] = a - i + 1
end
或者
for i = 0, b - 1 do -- the default increment is 1.
out[i + 1] = a - i
end
不同之处在于你在哪里做算术。
推荐阅读
- flutter - modalBottomSheet 被键盘覆盖
- c++ - 无法理解如何使用 SDF 字体的 stb_truetype 库计算与基线的垂直对齐方式?
- isabelle - 在伊莎贝尔中多次组合战术
- azure - 如何授权 Azure 逻辑应用 api 端点
- f# - 如何使用 FSharpx 的 PersistentVector 从索引 N 中删除一个项目?
- python - 在 IDLE 中识别但在 Atom 中不识别的导入模块
- sql - 如何正确编写查询以使用单个表的两个副本?
- python - 从 3D numpy 数组中删除索引
- r - 根据条件(位置)删除重复行
- java - 从 JAVA 程序执行的 VBA(宏)