import sys
import multiprocessing as mp
def make_tree(i, d):
if d:
d -= 1
return (i, make_tree(i, d), make_tree(i + 1, d))
return (i, None, None)
def check_tree(node):
i, l, r = node
if l is None:
return i
else:
return i + check_tree(l) - check_tree®
def make_check(itde, make=make_tree, check=check_tree):
i, d = itde
return check(make(i, d))
def get_argchunks(i, d, chunksize=5000):
assert chunksize % 2 == 0
chunk = []
for k in range(1, i + 1):
chunk.extend([(k, d), (-k, d)])
if len(chunk) == chunksize:
yield chunk
chunk = []
if len(chunk) > 0:
yield chunk
def main(n, min_depth=4):
max_depth = max(min_depth + 2, n)
stretch_depth = max_depth + 1
if mp.cpu_count() > 1:
pool = mp.Pool()
chunkmap = pool.map
else:
chunkmap = map
print('stretch tree of depth {}\t check: {}'.format(
stretch_depth, make_check((0, stretch_depth))))
mmd = max_depth + min_depth
for d in range(min_depth, stretch_depth, 2):
i = 2 ** (mmd - d)
cs = sum((sum(chunkmap(make_check, argchunk))
for argchunk in get_argchunks(i, d)))
print('{}\t trees of depth {}\t check: {}'.format(i * 2, d, cs))
print('long lived tree of depth {}\t check: {}'.format(
max_depth, make_check((0, max_depth))))
if __name__ == '__main__':
main(int(sys.argv[1]))
def item_check(left, item, right)
return item if left.nil?
item + item_check(*left) - item_check(*right)
end
def bottom_up_tree(item, depth)
return [nil, item, nil] unless depth > 0
item_item = 2 * item
depth -= 1
[bottom_up_tree(item_item - 1, depth), item, bottom_up_tree(item_item, depth)]
end
max_depth = ARGV[0].to_i
min_depth = 4
max_depth = min_depth + 2 if min_depth + 2 > max_depth
stretch_depth = max_depth + 1
stretch_tree = bottom_up_tree(0, stretch_depth)
puts "stretch tree of depth #{stretch_depth}\t check: #{item_check(*stretch_tree)}"
stretch_tree = nil
long_lived_tree = bottom_up_tree(0, max_depth)
min_depth.step(max_depth + 1, 2) do |depth|
iterations = 2**(max_depth - depth + min_depth)
check = 0
for i in 1..iterations
temp_tree = bottom_up_tree(i, depth)
check += item_check(*temp_tree)
temp_tree = bottom_up_tree(-i, depth)
check += item_check(*temp_tree)
end
puts "#{iterations * 2}\t trees of depth #{depth}\t check: #{check}"
end
puts "long lived tree of depth #{max_depth}\t check: #{item_check(*long_lived_tree)}"