Search code examples
arraysfor-looplua

How to create adaptable reversed array using For loop in Lua?


I need help to create this adaptable reversed array using for loop for my assignment

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()

any materials I can refer to will be very appreciated other than https://www.lua.org/pil/contents.html as i need more examples to understand the concepts.


Solution

  • 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()
    

    In the solution proposed, i is not only the iterator but also the value for the new table element. That is why it starts from a, ends at a - b + 1—this is the value of last element element of the needed table, since we need only b elements, and goes backwards (-1 increment).

    Alternatively, you can do:

        for i = 1, b do  -- the default increment is 1.
            out[i] = a - i + 1
        end
    

    or

        for i = 0, b - 1 do  -- the default increment is 1.
            out[i + 1] = a - i
        end
    

    The difference is where you do the arithmetics.