in reply to list to LoL

Here's my solution.... There's some unclean code in there to make it handle fencepost conditions that I could probably optimize out, but haven't yet. Would also be faster if I passed array references in and out of the reform_list subroutine.
use Data::Dumper; my @a=(1..100); my @a3=reform_list(3,@a); print Dumper(@a3); my @a4=reform_list(4,@a); print Dumper(@a4); sub reform_list{ my $size=shift; my @list=@_; my @nlist=(); my $max=int(scalar(@list)/$size); for(my $c=0;$c<=$max;$c++){ my $a=$c*$size; my $b=($c+1)*$size-1; if($b>=scalar(@list)){ $b=scalar(@list)-1; } if($a<=$b){ push @nlist,[@list[$a..$b]]; } } return @nlist; }
I've done some quick benchmarking and all 3 of the methods posted so far are very equivalent when it comes to performance (tests below are on a 1000 element array arranging it into sub-arrays of 5 elements each)
submitterbenchmark
adam6 wallclock secs ( 5.59 usr + 0.00 sys = 5.59 CPU) @ 894.45/s (n=5000)
lhoward6 wallclock secs ( 5.79 usr + 0.00 sys = 5.79 CPU) @ 863.56/s (n=5000)
swiftone6 wallclock secs ( 5.71 usr + 0.00 sys = 5.71 CPU) @ 875.66/s (n=5000)
Testing with other parameters (different list sizes and split sizes) shows different algorithms faster. All algorithms continue to stay very closely grouped performance wise (though I am happy to report that my algorithm appears to be slightly fastest for larger lists).

I've managed to clean up my code a little (though these changes didn't make it any faster). It doesn't look quite as ugly and still handles the fencepost conditions properly.

sub reform_list{ my $size=shift; my @list=@_; my @nlist=(); my $list_size=scalar(@list); my $c; my $stop=int($list_size/$size)*$size; for($c=0;$c<$stop;$c+=$size){ push @nlist,[@list[$c..($c+$size-1)]]; } if($c<$list_size){ push @nlist,[@list[$c..($list_size-1)]]; } return @nlist; }

Replies are listed 'Best First'.
RE: Re: list to LoL
by princepawn (Parson) on Jun 02, 2000 at 22:39 UTC
    lhoward and zzamboni are the

    greatest!!!!

    THANK YOU VERY MUCH!!!!

    You are both lifesavers. swiftone and adam, thank you very much as well.
      lhoward and zzamboni are the greatest!!!!

      You are welcome. Particularly since I did not post a reply to your question :-)

      --ZZamboni

      ps. Easy on the fonts there.