Well, at least writing these was enjoyable. Here are two solutions, both slightly adjusted to have data that does not evenly fit the number of bins.
modulo.pl:
#!/usr/bin/perl
use strict;
use warnings;
my @array = 1 .. 14;
use constant BINS => 4;
my @bins = ();
for my $i (0 .. $#array) {
print "i = $i:\t$array[$i]\n";
push @{$bins[$i % BINS]}, $array[$i];
}
use Data::Dumper;
print Dumper \@bins;
sample output:
i = 0: 1
i = 1: 2
i = 2: 3
i = 3: 4
i = 4: 5
i = 5: 6
i = 6: 7
i = 7: 8
i = 8: 9
i = 9: 10
i = 10: 11
i = 11: 12
i = 12: 13
i = 13: 14
$VAR1 = [
[
1,
5,
9,
13
],
[
2,
6,
10,
14
],
[
3,
7,
11
],
[
4,
8,
12
]
];
slice.pl
#!/usr/bin/perl
use strict;
use warnings;
my @array = 1 .. 14;
use constant BINS => 4;
my @bins = ();
for my $i (0 .. (BINS - 1)) {
push @bins, [@array[grep {defined $array[$_]}
map {BINS * $_ + $i} 0 .. (@array / BINS)]];
}
use Data::Dumper;
print Dumper \@bins;
sample output:
$VAR1 = [
[
1,
5,
9,
13
],
[
2,
6,
10,
14
],
[
3,
7,
11
],
[
4,
8,
12
]
];
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.