-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_trees.lua
50 lines (42 loc) · 1.19 KB
/
binary_trees.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
-- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Mike Pall
-- *reset*
local function BottomUpTree(depth)
if depth > 0 then
depth = depth - 1
local left, right = BottomUpTree(depth), BottomUpTree(depth)
return { left, right }
else
return { }
end
end
local function ItemCheck(tree)
if tree[1] then
return 1 + ItemCheck(tree[1]) + ItemCheck(tree[2])
else
return 1
end
end
local N = tonumber(arg and arg[1]) or 6
local mindepth = 4
local maxdepth = mindepth + 2
if maxdepth < N then maxdepth = N end
do
local stretchdepth = maxdepth + 1
local stretchtree = BottomUpTree(stretchdepth)
string.format("stretch tree of depth %d\t check: %d\n",
stretchdepth, ItemCheck(stretchtree))
end
local longlivedtree = BottomUpTree(maxdepth)
for depth=mindepth,maxdepth,2 do
local iterations = 2 ^ (maxdepth - depth + mindepth)
local check = 0
for i=1,iterations do
check = check + ItemCheck(BottomUpTree(depth))
end
string.format("%d\t trees of depth %d\t check: %d\n",
iterations, depth, check)
end
local check = ItemCheck(longlivedtree)
string.format("long lived tree of depth %d\t check: %d\n", maxdepth, check)