binary-tree.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. -- The Computer Language Benchmarks Game
  2. -- http://benchmarksgame.alioth.debian.org/
  3. -- contributed by Mike Pall
  4. local function BottomUpTree(item, depth)
  5. if depth > 0 then
  6. local i = item + item
  7. depth = depth - 1
  8. local left, right = BottomUpTree(i-1, depth), BottomUpTree(i, depth)
  9. return { item, left, right }
  10. else
  11. return { item }
  12. end
  13. end
  14. local function ItemCheck(tree)
  15. if tree[2] then
  16. return tree[1] + ItemCheck(tree[2]) - ItemCheck(tree[3])
  17. else
  18. return tree[1]
  19. end
  20. end
  21. local start = os.clock()
  22. local N = tonumber(arg and arg[1]) or 14
  23. local mindepth = 4
  24. local maxdepth = mindepth + 2
  25. if maxdepth < N then maxdepth = N end
  26. do
  27. local stretchdepth = maxdepth + 1
  28. local stretchtree = BottomUpTree(0, stretchdepth)
  29. io.write(string.format("stretch tree of depth %d\t check: %d\n",
  30. stretchdepth, ItemCheck(stretchtree)))
  31. end
  32. local longlivedtree = BottomUpTree(0, maxdepth)
  33. for depth=mindepth,maxdepth,2 do
  34. local iterations = 2 ^ (maxdepth - depth + mindepth)
  35. local check = 0
  36. for i=1,iterations do
  37. check = check + ItemCheck(BottomUpTree(1, depth)) +
  38. ItemCheck(BottomUpTree(-1, depth))
  39. end
  40. io.write(string.format("%d\t trees of depth %d\t check: %d\n",
  41. iterations*2, depth, check))
  42. end
  43. io.write(string.format("long lived tree of depth %d\t check: %d\n",
  44. maxdepth, ItemCheck(longlivedtree)))
  45. print("binary-tree", N, os.clock()-start)