http://qs321.pair.com?node_id=117484


in reply to (Golf) Building a Better Binary Tree

Just to get things started...

However I'm definitely not proud of this code. Whitespace has not been taken out for clarity.

The function basically outputs the worst possible tree after sorting the array, each left leaf is always 0 and the right is built iteratively, thus not using recursion. Since building strings is much easier than building trees (no pun intended), I did exactly that, evalling the result. It is a hash, not a reference, as the example code seems to suggest. Outputting a ref would allow some more savings :-)

Warning: for $func to work properly with sort, it should be prototyped:
my $func = sub($$) { $_[0] <=> $_[1] };

And now the code:

sub buildtree { my($f, @a) = @_; local $_; @a = ((sort $f @a), ''); $_ = join '=>[0,{', @a; chop; $_ = '(' . $_ . '0' . ']}' x $#a; s/}$/)/; eval; }

It should be 103 chars excluding function declaration and non significative whitespace.

It can be tested in this context:

#!/usr/bin/perl -w use strict; use Data::Dumper; sub buildtree { my($f, @a) = @_; local $_; @a = ((sort $f @a), ''); $_ = join '=>[0,{', @a; chop; $_ = '(' . $_ . '0' . ']}' x $#a; s/}$/)/; eval; } my @array = ( 6, 1, 2, 3, 4, 5 ); my $func = sub($$) { $_[0] <=> $_[1] }; my %tree = buildtree( $func, @array ); print Dumper \%tree;

Update: In the initial post I forgot to add the character count :-)

Update 2: After tilly's comment I changed the function so that there's no need to prototypes, and I took some time to compress it further down to 88 chars:

# 1 2 3 4 #23456789012345678901234567890123456789012345 my$f=shift;@_=((sort{&$f($a,$b)}@_),'');$_= join'=>[0,{',@_;chop;%{eval"{$_ 0".']}'x$#_};

-- TMTOWTDI