Do you need to save all permutations in advance? You can generate them on the fly instead.
Example:
local function genPerm(self, i) local result = {} local f = 1 for j = 1, self.n do f = f * j table.insert(result, j) end for j = 1, self.n-1 do f = f / (self.n + 1 - j) local k = math.floor((i - 1) / f) table.insert(result, j, table.remove(result, j+k)) i = i - k * f end return result end local function perms(n) return setmetatable({n=n}, {__index=genPerm}) end local generator = perms(11) for _, i in ipairs {1, 42, 1000000, 39916800} do print(table.concat(generator[i], ',')) end
finnw source share