binary-tree2.nut 1.5 KB

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