Skip to content

Instantly share code, notes, and snippets.

@1nn3
Last active July 19, 2020 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1nn3/a5e856369bdd3859ee755729f605053c to your computer and use it in GitHub Desktop.
Save 1nn3/a5e856369bdd3859ee755729f605053c to your computer and use it in GitHub Desktop.
Teile eine Liste in gleichlange Teile
#!/usr/bin/env perl
use Data::Dumper;
use POSIX;
#** @method public listsplit ()
# @brief split a list into equal length portions
#
# Teilt eine Liste in N gleiche Portionen auf.
# Beachte: Bleibt ein Rest, sind es N+1 Portionen. Ist $portions >
# scalar(@array), sind es nur scalar(@array) Portionen.
#
# @param $portions Anzahl Portionen
# @param @list Die aufzuteilende Liste
# @retval @list portions as array of arrays
#*
sub listsplit {
my ( $portions, @array ) = @_;
my @aoa = (); # array of arrays
if ( $portions > scalar(@array) ) {
$portions = scalar(@array);
}
if ( $portions <= 0 ) {
return @aoa;
}
my $portion_length = floor( scalar(@array) / $portions );
if ( $portion_length <= 0 ) {
return @aoa;
}
for ( my $i = 0 ; $i < $portions ; $i++ ) {
push @aoa, [ splice( @array, 0, $portion_length ) ];
}
# rest if any
my $rest = scalar(@array) % $portions;
if ($rest) {
push @aoa, [ splice( @array, 0, $rest ) ];
}
return @aoa;
}
print Dumper(
listsplit( ceil(3), ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ) ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment