Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: (Golf) Building a Better Binary Tree

by trantor (Chaplain)
on Oct 08, 2001 at 19:53 UTC ( #117484=note: print w/replies, xml ) Need Help??


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

Replies are listed 'Best First'.
Re (tilly) 2: (Golf) Building a Better Binary Tree
by tilly (Archbishop) on Oct 09, 2001 at 22:33 UTC
    The spec did not say you could assume a prototyped comparison function, and the example given in the spec was not prototyped. Therefore I do not consider this a solution. (If we could change conditions, I would love to put the subroutine at the end so I could pop rather than shift. No go.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://117484]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2023-11-29 13:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?