Dividing a list of numbers based on given criteria
I have a list with following numbers:
1,2,3,4,5,6,7,8,9,10,11 ..... (This is not a arithmetic progression. some numbers might missing in the list)
I have three indexes 1,2,3
I want to divide this list into three groups.
1 will contain 1,4,7
2 will contain 2,5,8
3 will contain 3,6,9
Please suggest me some good optimize开发者_运维知识库d way to do that as the list is almost 10,000 number long.
I will request for an algo or a program in Perl.
-Ravi
There is also part
function available from List::MoreUtils core package. It can partition list based on any criteria. If you want position % 3
, here is an example:
use List::MoreUtils qw(part);
use Data::Dump;
my @list = (1,2,3,4,5,6,7,8,9,10,11);
my $i;
my @part = part { $i++ % 3 } @list;
dd [@part];
# prints [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9]]
use strict;
use warnings;
use 5.010;
use Data::Dumper;
my @array = (1,2,3,4,5,6,7,8,9,10,11);
my %hash;
map { push @{$hash{$_ % 3}}, $array[$_] } 0..$#array;
say Dumper \%hash;
You'll probably have to add an extra line inside the map if you want the hash keys to be something more significant.
I don't see exactly what you want, but as far as i could understand, have a try with:
#!perl
use strict;
use warnings;
use 5.10.1;
use Data::Dumper;
my @list = (1..12);
my @ind = (1,2,3);
my @result;
for (my $i=0; $i<@list; $i+=@ind) {
for (my $j=0; $j<@ind; $j++) {
push @{$result[$j]}, $list[$i+$j];
}
}
say Dumper \@result;
精彩评论