Projects

Ticket #566: binary-trees.rb

File binary-trees.rb, 1.2 KB (added by peter@…, 2 years ago)

binary trees benchmark that causes the memory usage

Line 
1# The Computer Language Shootout Benchmarks
2# http://shootout.alioth.debian.org
3#
4# contributed by Jesse Millikan
5# Modified by Wesley Moxam
6
7def item_check(left, item, right)
8  return item if left.nil?
9  item + item_check(*left) - item_check(*right)
10end
11
12def bottom_up_tree(item, depth)
13  return [nil, item, nil] unless depth > 0
14  item_item = 2 * item
15  depth -= 1
16  [bottom_up_tree(item_item - 1, depth), item, bottom_up_tree(item_item, depth)]
17end
18
19max_depth = ARGV[0].to_i
20min_depth = 4
21
22max_depth = min_depth + 2 if min_depth + 2 > max_depth
23
24stretch_depth = max_depth + 1
25stretch_tree = bottom_up_tree(0, stretch_depth)
26
27puts "stretch tree of depth #{stretch_depth}\t check: #{item_check(*stretch_tree)}"
28stretch_tree = nil
29
30long_lived_tree = bottom_up_tree(0, max_depth)
31
32min_depth.step(max_depth + 1, 2) do |depth|
33  iterations = 2**(max_depth - depth + min_depth)
34
35  check = 0
36
37  for i in 1..iterations
38    temp_tree = bottom_up_tree(i, depth)
39    check += item_check(*temp_tree)
40
41    temp_tree = bottom_up_tree(-i, depth)
42    check += item_check(*temp_tree)
43  end
44
45  puts "#{iterations * 2}\t trees of depth #{depth}\t check: #{check}"
46end
47
48puts "long lived tree of depth #{max_depth}\t check: #{item_check(*long_lived_tree)}"