factor/extra/benchmark/binary-trees/binary-trees.factor

58 lines
1.4 KiB
Factor
Raw Normal View History

2008-04-20 06:15:46 -04:00
USING: kernel math accessors prettyprint io locals sequences
2008-04-26 12:03:41 -04:00
math.ranges math.order ;
2008-04-20 06:15:46 -04:00
IN: benchmark.binary-trees
TUPLE: tree-node item left right ;
C: <tree-node> tree-node
: bottom-up-tree ( item depth -- tree )
dup 0 > [
1 -
[ drop ]
2008-12-17 20:28:07 -05:00
[ [ 2 * 1 - ] dip bottom-up-tree ]
[ [ 2 * ] dip bottom-up-tree ] 2tri
2008-04-20 06:15:46 -04:00
] [
drop f f
] if <tree-node> ; inline recursive
2008-04-20 06:15:46 -04:00
GENERIC: item-check ( node -- n )
M: tree-node item-check
[ item>> ] [ left>> ] [ right>> ] tri [ item-check ] bi@ - + ;
M: f item-check drop 0 ;
: min-depth 4 ; inline
: stretch-tree ( max-depth -- )
1 + 0 over bottom-up-tree item-check
[ "stretch tree of depth " write pprint ]
[ "\t check: " write . ] bi* ; inline
2008-04-20 06:15:46 -04:00
:: long-lived-tree ( max-depth -- )
0 max-depth bottom-up-tree
min-depth max-depth 2 <range> [| depth |
max-depth depth - min-depth + 2^ [
[1,b] 0 [
dup neg
[ depth bottom-up-tree item-check + ] bi@
2008-04-20 06:15:46 -04:00
] reduce
]
[ 2 * ] bi
pprint "\t trees of depth " write depth pprint
"\t check: " write .
] each
"long lived tree of depth " write max-depth pprint
"\t check: " write item-check . ; inline
: binary-trees ( n -- )
min-depth 2 + max [ stretch-tree ] [ long-lived-tree ] bi ; inline
: binary-trees-main ( -- )
16 binary-trees ;
2008-05-07 22:37:12 -04:00
MAIN: binary-trees-main