Last active
July 19, 2020 06:47
-
-
Save 1nn3/a5e856369bdd3859ee755729f605053c to your computer and use it in GitHub Desktop.
Teile eine Liste in gleichlange Teile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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