Perl - split array into smaller uniformly distributed arrays

How would I split a Perl array of arbitrary size into a variable number of smaller arrays with the number of elements in each smaller array that was distributed as evenly? The original array should not be destroyed.

+3
source share
4 answers

Above my head:

use strict;
use warnings;

use Data::Dumper; # for debugging only 

print Dumper(distribute(7, [1..30]));

# takes number+arrayref, returns ref to array of arrays
sub distribute {
    my ($n, $array) = @_;

    my @parts;
    my $i = 0;
    foreach my $elem (@$array) {
        push @{ $parts[$i++ % $n] }, $elem;
    };
    return \@parts;
};

This ensures that the number of elements in @parts can only differ by one. There is another solution that pre-calculated numbers and used splicing:

push @parts, [ @$array[$offset..$offset+$chunk] ];
$offset += chunk;
# alter $chunk if needed. 
+8
source

Here the version of List :: MoreUtils is used:

use strict;
use warnings;

use List::MoreUtils qw(part);

use Data::Dumper;

my @array = 1..9;
my $partitions = 3;

my $i = 0;

print Dumper part {$partitions * $i++ / @array} @array;
+5
source

, :

use strict;
use warnings;

use List::MoreUtils qw(part);
use Data::Dumper;

my $i = 0;
my $numParts = 2;
my @part = part { $i++ % $numParts } 1 .. 30; 
print Dumper @part;
+1

@Dallaylaen , Perl. ( , Dallaylaen ) :

    my @arrayIn = (1..30);
    my @arrayOfArrays = distribute(7, \@arrayIn);
    sub distribute {
        my ($n, $array) = @_;

        my @parts;
        my $i = 0;
        foreach my $elem (@$array) {
            push @{ $parts[$i++ % $n] }, $elem;
        };
        return @parts;
    };
+1

All Articles