Skip to content

Bogosort in lua #413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions contents/bogo_sort/bogo_sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ In code, it looks something like this:
[import:17-20, lang:"haskell"](code/haskell/bogoSort.hs)
{% sample lang="m" %}
[import:21-28, lang:"matlab"](code/matlab/bogosort.m)
{% sample lang="lua" %}
[import:1-22, lang="lua"](code/lua/bogosort.lua)
{% sample lang="cpp" %}
[import:33-38, lang:"c_cpp"](code/c++/bogosort.cpp)
{% sample lang="rs" %}
Expand Down Expand Up @@ -73,6 +75,8 @@ We are done here!
[import, lang:"haskell"](code/haskell/bogoSort.hs)
{% sample lang="m" %}
[import, lang:"matlab"](code/matlab/bogosort.m)
{% sample lang="lua" %}
[import, lang="lua"](code/lua/bogosort.lua)
{% sample lang="cpp" %}
[import, lang:"c_cpp"](code/c++/bogosort.cpp)
{% sample lang="rs" %}
Expand Down
28 changes: 28 additions & 0 deletions contents/bogo_sort/code/lua/bogosort.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
local function shuffle(arr)
for i = 1, #arr-1 do
local rand = math.random(i,#arr)
arr[i], arr[rand] = arr[rand], arr[i]
end
end

local function issorted(arr)
for i = 1,#arr-1 do
if arr[i] > arr[i+1] then
return false
end
end
return true
end

function bogosort(arr)
while not issorted(arr) do
shuffle(arr)
end
end

local arr = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it ever finish with 10 elements? :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not underestimate the speed of lua, only takes 5 seconds on my slow laptop.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hahaha fair enough :D

print(("Unsorted array: {%s}"):format(table.concat(arr,", ")))

bogosort(arr)

print(("Sorted array: {%s}"):format(table.concat(arr,", ")))