Skip to content

Instantly share code, notes, and snippets.

@valtoni
Last active November 1, 2018 16:33
Show Gist options
  • Save valtoni/f1933867ec70fd37f3925f09d7667a31 to your computer and use it in GitHub Desktop.
Save valtoni/f1933867ec70fd37f3925f09d7667a31 to your computer and use it in GitHub Desktop.
Programming in Lua 4th edition. Chapter 6: Functions
-- Exercise 6.4: Write a function to shuffle a given list. Make sure that all permutations are equally probable.
function q4(...)
items = table.pack(...)
itemsr = {}
for i=1,#items do
math.randomseed(os.time())
pick = math.random(#items)
print("Picked item:", pick)
table.insert(itemsr,items[pick])
table.remove(items, pick)
end
return table.unpack(itemsr)
end
-- Write a funcion that takes an array and prints all combinations of the elements in the array.
-- (Hint: you can use recursive formula for combination: C(n,m)=C(n-1,m-1)+C(n-1,m). To generate
-- all C(n,m) combinations of n elements in groups of size m, you fist add the firs element to
-- the result and then generate all C(n-1,m-1) combinations of the remaining elements in the
-- remaining slots; then you remove the first element from the result and then generate all
-- C(n-1,m) combinations of the remaining elements in the free slots. When n is smaller than m,
-- there are no combinations. When m is zero, there is only one combination, which uses no
-- elements.)
--
-- User: valtoni
-- Date: 31/10/18
-- Time: 12:12
-- To change this template use File | Settings | File Templates.
--
function combs(items, x, y)
local m, n = x, y
if m == nil then
m = #items - 1
end
if n == nil then
n = #items
print("FIRST LEVEL")
end
if m * n == 0 then
print("EXITED (NO LEVEL ANYMORE)")
return {{}}
end
local ret, old = {}, combs(items, m-1, n-1)
for i = 1, n do
for k, v in ipairs(old) do
ret[#ret+1] = {i, map(incr(i), table.unpack(v))}
end
end
retplain={{}}
if x == nil then
for i=1,#ret do
item = ret[i]
plain = {}
for j=1,#item do
table.insert(plain, items[item[j]])
end
table.insert(retplain, plain)
end
print("FIRST LEVEL")
return retplain
else
print("LEVEL", x, y)
return ret
end
end
function map(f, a, ...)
if a then
return f(a), map(f, ...)
end
end
function incr(k)
return
function(a)
return k > a and a or a+1
end
end
r=combs({"banana", "avocado", "pinneaple", "apple"})
for i=1,#r do
print(table.unpack(r[i]))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment