binary-tree.nut 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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){
  6. local i = item + item;
  7. --depth;
  8. return [ item, BottomUpTree(i-1, depth), BottomUpTree(i, depth) ];
  9. }
  10. return [ item ];
  11. }
  12. local function ItemCheck(tree){
  13. if (tree.get(1, false)) return tree[0] + ItemCheck(tree[1]) - ItemCheck(tree[2])
  14. return tree[0]
  15. }
  16. local start = os.clock()
  17. //check_delayed_release_hooks(false);
  18. local N = vargv.get(1, 14).tointeger();
  19. local mindepth = 4
  20. local maxdepth = mindepth + 2
  21. if (maxdepth < N) maxdepth = N
  22. {
  23. local stretchdepth = maxdepth + 1
  24. local stretchtree = BottomUpTree(0, stretchdepth)
  25. print(format("stretch tree of depth %d\t check: %d",
  26. stretchdepth, ItemCheck(stretchtree)))
  27. }
  28. local longlivedtree = BottomUpTree(0, maxdepth)
  29. for(local depth=mindepth; depth <= maxdepth; depth += 2){
  30. local iterations = math.pow(2, (maxdepth - depth + mindepth)).tointeger()
  31. local check = 0
  32. for(local i=0; i < iterations; ++i){
  33. check += ItemCheck(BottomUpTree(1, depth)) +
  34. ItemCheck(BottomUpTree(-1, depth))
  35. }
  36. print(format("%d\t trees of depth %d\t check: %d",
  37. iterations*2, depth, check))
  38. }
  39. print(format("long lived tree of depth %d\t check: %d\n",
  40. maxdepth, ItemCheck(longlivedtree)))
  41. print("binary-tree", N, os.clock()-start)