Last active
December 2, 2015 06:01
-
-
Save diakopter/1629c6704534eeed1afb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TreeNode { | |
| has Int $!item; | |
| has TreeNode $!left; | |
| has TreeNode $!right; | |
| method spawn(Int \item, Int \depth) { | |
| return ChildTreeNodes(item, depth - 1); | |
| } | |
| sub ChildTreeNodes(Int \item, Int \depth) | |
| { | |
| return TreeNode.new(:item, :left(TreeNode), :right(TreeNode)) unless depth; | |
| return TreeNode.new(:item, | |
| :left(ChildTreeNodes(2 * item - 1, depth - 1)), | |
| :right(ChildTreeNodes(2 * item, depth - 1))); | |
| } | |
| submethod BUILD(:$!item, :$!left, :$!right) {} | |
| method check() { | |
| $!left ?? $!left.check() - $!right.check() + $!item !! $!item; | |
| } | |
| } | |
| my int $n = 16; | |
| my int $minDepth = 4; | |
| my int $maxDepth = max($minDepth + 2, $n); | |
| my int $stretchDepth = $maxDepth + 1; | |
| my int $check = (TreeNode.spawn(0, $stretchDepth)).check(); | |
| say "stretch tree of depth $stretchDepth\t check: $check"; | |
| my TreeNode $longLivedTree = TreeNode.spawn(0, $maxDepth); | |
| loop (my int $depth = $minDepth; $depth <= $maxDepth; $depth += 2) { | |
| my int $iterations = 1 +< ($maxDepth - $depth + $minDepth); | |
| $check = 0; | |
| loop (my int $i = 1; $i <= $iterations; $i++) { | |
| $check += (TreeNode.spawn($i, $depth)).check(); | |
| $check += (TreeNode.spawn(-$i, $depth)).check(); | |
| } | |
| say "{$iterations +< 1}\t trees of depth $depth\t check: $check"; | |
| } | |
| say "long lived tree of depth $maxDepth\t check: {$longLivedTree.check()}"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment