Advertisement
snake5

binarytrees.sgs

Sep 8th, 2016
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. // The Computer Language Benchmarks Game
  2. // http://benchmarksgame.alioth.debian.org/
  3.  
  4. include "string", "math";
  5.  
  6. function BottomUpTree( item, depth )
  7. {
  8.   if( depth > 0 )
  9.   {
  10.     i = item + item;
  11.     depth = depth - 1;
  12.     left = BottomUpTree(i-1, depth);
  13.     right = BottomUpTree(i, depth);
  14.     return [item, left, right];
  15.   }
  16.   else
  17.   {
  18.     return [item];
  19.   }
  20. }
  21.  
  22. function ItemCheck(tree)
  23. {
  24.   if( @tree[1] )
  25.     return tree[0] + ItemCheck(tree[1]) - ItemCheck(tree[2]);
  26.   else
  27.     return tree[0];
  28. }
  29.  
  30. var N = toreal(@argv[1]) ?? 0.0;
  31. var mindepth = 4;
  32. var maxdepth = mindepth + 2;
  33. if( maxdepth < N ) maxdepth = N;
  34.  
  35. {
  36.   var stretchdepth = maxdepth + 1;
  37.   var stretchtree = BottomUpTree(0, stretchdepth);
  38.   print(string_format("stretch tree of depth {1:d}\t check: {2:d}\n",
  39.     stretchdepth, ItemCheck(stretchtree)));
  40. }
  41.  
  42. var longlivedtree = BottomUpTree(0, maxdepth);
  43.  
  44. for( depth=mindepth; depth <= maxdepth; depth += 2 )
  45. {
  46.   var iterations = pow( 2, maxdepth - depth + mindepth);
  47.   var check = 0;
  48.   for( i=1; i <= iterations; ++i)
  49.   {
  50.     check = check + ItemCheck(BottomUpTree(1, depth)) +
  51.             ItemCheck(BottomUpTree(-1, depth));
  52.   }
  53.   print(string_format("{1:d}\t trees of depth {2:d}\t check: {3:d}\n",
  54.     iterations*2, depth, check));
  55. }
  56.  
  57. print(string_format("long lived tree of depth {1:d}\t check: {2:d}\n",
  58.   maxdepth, ItemCheck(longlivedtree)));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement