Skip to content

Instantly share code, notes, and snippets.

@Bradshaw
Created November 20, 2018 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bradshaw/5d2bf8a10fdab3f5b15e8a95680bbd82 to your computer and use it in GitHub Desktop.
Save Bradshaw/5d2bf8a10fdab3f5b15e8a95680bbd82 to your computer and use it in GitHub Desktop.
Horrible Sort in Lua
-- Creates a table containing the values 1 through num
function tableOf(num)
local t = {}
for i=1,num do
t[i] = i
end
return t
end
-- Shuffles a table
function shuffle(t)
for i=1,#t do
local pick = math.random(i,#t)
t[i],t[pick] = t[pick],t[i]
end
return t
end
-- Sorts a table with the bubblesort method
function bubbleSort(t)
local sorted = false
while not sorted do
sorted = true
for i=2,#t do
steps = steps + 1
if compare(t[i-1], t[i])>0 then
sorted = false
t[i], t[i-1] = t[i-1], t[i]
end
end
end
return t
end
-- This is the most terrible sorting algorithing I've ever made
-- With depth==0, run a bubblesort
-- With depth>0, create all permutations of the table, and then sort those with depth-1
function sillySort(t, depth)
print("Depth: ", depth)
if depth==0 then
return bubbleSort(copy(t))
end
local perms = makePermutations(t);
ps = ps+#perms
sillySort(perms, depth-1)
return perms[1]
end
-- Creates a shallow copy of a table, optionally excluding an element
function copy(t, without)
local c = {}
for i,v in ipairs(t) do
if not (without and i==without) then
table.insert(c, v)
end
end
return c
end
-- Concatenates t2 to the end of t1
function concat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- Create all permutations of a table
function makePermutations(t)
if #t==1 then
return {t}
end
local perms = {}
for i,v in ipairs(t) do
for j,u in ipairs(makePermutations(copy(t,i))) do
table.insert(perms, concat({v},u))
end
end
return perms
end
-- Compare two numbers or tables
function compare(a, b)
if type(a)=="number" then
return numCompare(a, b)
else
return arrayCompare(a, b)
end
end
-- Compare two numbers, return -1 if a<b, 1 if a>b and 0 if a==b
function numCompare(a, b)
return a==b and 0 or (a<b and -1 or 1)
end
-- Compare two arrays by returning the numCompare of the first differing value, or 0 if both arrays are equal
function arrayCompare(a, b)
for i=1,#a do
local comp = compare(a[i],b[i])
if comp ~= 0 then
return comp
end
end
return 0
end
-- Test
math.randomseed(os.time())
for i=1,1000000 do
math.random()
end
for elements=1,4 do
for depth=0,3 do
print("Elements: "..elements)
print("To depth: "..depth)
steps = 0
ps = 0
local t = shuffle(tableOf(elements))
local at = sillySort(t,depth)
print("permutations: "..ps)
print("Comparisons: "..steps)
print()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment