| 1 | # The Computer Language Shootout Benchmarks |
|---|
| 2 | # http://shootout.alioth.debian.org |
|---|
| 3 | # |
|---|
| 4 | # contributed by Jesse Millikan |
|---|
| 5 | # Modified by Wesley Moxam |
|---|
| 6 | |
|---|
| 7 | def item_check(left, item, right) |
|---|
| 8 | return item if left.nil? |
|---|
| 9 | item + item_check(*left) - item_check(*right) |
|---|
| 10 | end |
|---|
| 11 | |
|---|
| 12 | def 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)] |
|---|
| 17 | end |
|---|
| 18 | |
|---|
| 19 | max_depth = ARGV[0].to_i |
|---|
| 20 | min_depth = 4 |
|---|
| 21 | |
|---|
| 22 | max_depth = min_depth + 2 if min_depth + 2 > max_depth |
|---|
| 23 | |
|---|
| 24 | stretch_depth = max_depth + 1 |
|---|
| 25 | stretch_tree = bottom_up_tree(0, stretch_depth) |
|---|
| 26 | |
|---|
| 27 | puts "stretch tree of depth #{stretch_depth}\t check: #{item_check(*stretch_tree)}" |
|---|
| 28 | stretch_tree = nil |
|---|
| 29 | |
|---|
| 30 | long_lived_tree = bottom_up_tree(0, max_depth) |
|---|
| 31 | |
|---|
| 32 | min_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}" |
|---|
| 46 | end |
|---|
| 47 | |
|---|
| 48 | puts "long lived tree of depth #{max_depth}\t check: #{item_check(*long_lived_tree)}" |
|---|