Skip to content

Commit fa81a55

Browse files
committed
Added 100 doors problem
1 parent 482ab31 commit fa81a55

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
-- 100 doors problem implementation
2+
-- See : http://rosettacode.org/wiki/100_doors
3+
4+
-- Collects keys of values matching a predicate
5+
local function collect(t, v)
6+
local s = {}
7+
for k,_v in ipairs(t) do
8+
if _v == v then s[#s+1] = k end
9+
end
10+
return s
11+
end
12+
13+
-- Simulates the 100 doors problem
14+
-- returns : a table of all open doors
15+
-- a table of all closed doors
16+
local function hundred_doors()
17+
local doors = {}
18+
for mp = 1, 100 do
19+
for i = mp, 100, mp do
20+
doors[i] = (doors[i] == nil and false or not doors[i])
21+
end
22+
end
23+
return collect(doors, true), collect(doors, false)
24+
end
25+
26+
return hundred_doors
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
-- Tests for 100doors.lua
2+
local hundred_doors = require '100doors'
3+
4+
local total, pass = 0, 0
5+
6+
local function dec(str, len)
7+
return #str < len
8+
and str .. (('.'):rep(len-#str))
9+
or str:sub(1,len)
10+
end
11+
12+
local function run(message, f)
13+
total = total + 1
14+
local ok, err = pcall(f)
15+
if ok then pass = pass + 1 end
16+
local status = ok and 'PASSED' or 'FAILED'
17+
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
18+
end
19+
20+
run('Open doors are perfect squares of integers', function()
21+
local open, closed = hundred_doors()
22+
for i, v in ipairs(open) do
23+
assert(math.floor(math.sqrt(v)) == math.sqrt(v))
24+
end
25+
end)
26+
27+
print(('-'):rep(80))
28+
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
29+
:format(total, pass, total-pass, (pass*100/total)))

100_Doors_Problem/tags

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Puzzle

0 commit comments

Comments
 (0)