【问题标题】:How to create adaptable reversed array using For loop in Lua?如何在 Lua 中使用 For 循环创建自适应反转数组?
【发布时间】:2021-01-13 05:40:57
【问题描述】:

我需要帮助来使用 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 之外,我可以参考的任何材料都将不胜感激 因为我需要更多示例来理解这些概念。

【问题讨论】:

    标签: arrays for-loop lua


    【解决方案1】:
    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
    

    不同之处在于你在哪里做算术。

    【讨论】:

    • 感谢您的回答,它正在起作用,但您能解释一下它背后的原因吗?即为什么从 4 开始,并使用 a-b+1?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2022-08-11
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多