Created
July 16, 2012 10:59
-
-
Save balaam/3122129 to your computer and use it in GitHub Desktop.
Reverse an ipairs table in Lua (not clever O(n) could be O(n/2) with swapping)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- Reverses an ipairs table | |
-- | |
--local r = ReverseTable({'a', 'b', 'c'}) | |
--for k, v in ipairs(r) do | |
-- print(k, v) | |
--end | |
-- | |
-- | |
function ReverseTable(t) | |
local reversedTable = {} | |
local itemCount = #t | |
for k, v in ipairs(t) do | |
reversedTable[itemCount + 1 - k] = v | |
end | |
return reversedTable | |
end |
^ agreed
If you don't mind modifying the original talbe, this should do the trick for O(n/2):
function reverse(tbl)
for i=1, math.floor(#tbl / 2) do
local tmp = tbl[i]
tbl[i] = tbl[#tbl - i + 1]
tbl[#tbl - i + 1] = tmp
end
end
It's even a line shorter 😄
function reverse(tbl)
for i=1, math.floor(#tbl / 2) do
tbl[i], tbl[#tbl - i + 1] = tbl[#tbl - i + 1], tbl[i]
end
end
Isn't this one working too?
O(n/2) is O(n)
I think you mean n/2, without the O
function table.reverse(t)
local len = #t
for i = len - 1, 1, -1 do
t[len] = table.remove(t, i)
end
end
or modified ipairs-function
function rpairs(t)
return function(t, i)
i = i - 1
if i ~= 0 then
return i, t[i]
end
end, t, #t + 1
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tohle funguje