in reply to Filling buckets

This was what I came up with after a few minutes. This solution sort of "grew", so I wouldn't be surprised if there was a more elegant way of doing it.
sub split_into_three { my $first = @_; my $last = int($first / 3); $first -= $last; $first -= int($first / 2); return [ @_[0..$first-1] ], [ @_[$first..$#_-$last] ], [ @_[$#_-$last+1..$#_] ]; } my ($first, $second, $third) = split_into_three(@everything); my @buckets = split_into_three('a'..'z'); print join("\n", map { join(" ", @{$_}) } @buckets), "\n"; # a b c d e f g h i # j k l m n o p q r # s t u v w x y z

Replies are listed 'Best First'.
Re: Re: Filling buckets
by Fastolfe (Vicar) on Jan 03, 2001 at 08:42 UTC
    Here's a nicer solution (IMO) using splice:
    sub split_into { my $howmany = shift; my @from = reverse @_; my @buckets; unshift(@buckets, [ reverse splice(@from, 0, @from / $howmany--) ]) + while $howmany; @buckets; }
    Or, dropping @buckets at the expense of readability (and perhaps efficiency):
    sub split_into { my $howmany = shift; my @from = reverse @_; reverse map { [ reverse splice(@from, 0, @from / $_) ] } reverse 1 .. $howmany; }

      ...but that second example just looks good...