Skip to content

Commit

Permalink
Added 100 doors problem
Browse files Browse the repository at this point in the history
  • Loading branch information
Yonaba committed Mar 22, 2014
1 parent 482ab31 commit fa81a55
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 100_Doors_Problem/Lua/Yonaba/100doors.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
-- 100 doors problem implementation
-- See : http://rosettacode.org/wiki/100_doors

-- Collects keys of values matching a predicate
local function collect(t, v)
local s = {}
for k,_v in ipairs(t) do
if _v == v then s[#s+1] = k end
end
return s
end

-- Simulates the 100 doors problem
-- returns : a table of all open doors
-- a table of all closed doors
local function hundred_doors()
local doors = {}
for mp = 1, 100 do
for i = mp, 100, mp do
doors[i] = (doors[i] == nil and false or not doors[i])
end
end
return collect(doors, true), collect(doors, false)
end

return hundred_doors
29 changes: 29 additions & 0 deletions 100_Doors_Problem/Lua/Yonaba/100doors_test.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
-- Tests for 100doors.lua
local hundred_doors = require '100doors'

local total, pass = 0, 0

local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end

local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end

run('Open doors are perfect squares of integers', function()
local open, closed = hundred_doors()
for i, v in ipairs(open) do
assert(math.floor(math.sqrt(v)) == math.sqrt(v))
end
end)

print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
1 change: 1 addition & 0 deletions 100_Doors_Problem/tags
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Puzzle

0 comments on commit fa81a55

Please sign in to comment.