首页 > 解决方案 > 如何在 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之外,我可以参考的任何材料都将不胜感激, 因为我需要更多示例来理解这些概念。

标签: arraysfor-looplua

解决方案


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

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


推荐阅读