-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03.lua
32 lines (28 loc) · 852 Bytes
/
03.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
-- Derangements
-- Helper: Print a list:
function printResult (a)
for i,v in ipairs(a) do io.write(v, " ") end
io.write("\n")
end
-- Generate a Derangement:
-- Swap element at index i with last element and recurse.
-- Dont swap if we would put i in the i-th slot.
function derangement (a, n)
if n == 1 then
coroutine.yield(a)
else
for i=1,n do
if ((a[i] ~= n) and ( a[n] ~= i)) then
a[n], a[i] = a[i], a[n] -- swap i-th and n-th element
derangement(a, n - 1) -- generate all permutations of the other elements
a[n], a[i] = a[i], a[n] -- restore i-th element
end
end
end
end
-- Generator using coroutine.wrap:
-- Usage: for i in derange(sequence) do ... end
function derange (a)
local n = table.getn(a) -- length of list
return coroutine.wrap(function () derangement(a, n) end)
end