Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

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


In reply to Re: (Golf) Building a Better Binary Tree by trantor
in thread (Golf) Building a Better Binary Tree by Masem

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.