Contributed by Blanco
on Apr 05, 2002 at 23:49 UTC
Q&A
> arrays
Description: How can I skip an element in an array whilst reading data from each 'side' of the array into two seperate arrays, eg:
input from an array already pre-defined:
2022, 2002
6, 78
1023, 1232
I would like two arrays like so:
array 1: 2022
6
1023
array 2: 2002
78
1232
The array will be very large and may change in length.
Cheers Answer: How can I skip an element in an array whilst reading... contributed by tachyon For a non-destructive method that leaves the original array intact (we use a modulus flip-flop):
for my $i ( 0 .. $#in ) {
$i % 2 ? push @out2, $in[$i] : push @out1, $in[$i];
}
| Answer: How can I skip an element in an array whilst reading... contributed by belg4mit I fail to see where the "either side" comes from....
If you mean your array is:
2022, 2002, 6, 78 1023, 1232
Then the following should work:
while( @in ){
push @out1, shift(@in);
push @out2, shift(@in);
}
| Answer: How can I skip an element in an array whilst reading... contributed by tachyon This C style approach is 50% faster than the push approach posted earlier. Ugly but fast.
use Benchmark;
@in = (1,2,3,4,5,6,7,8,9,0);
timethese ( 100000, {
'C-style' =>
'for my $i ( 0 .. $#in ) {
$i % 2 ? $out2[int($i/2)] = $in[$i] : $out1[$i/2] = $i
+n[$i]
}',
'push' =>
'for my $i ( 0 .. $#in ) {
$i % 2 ? push @out2, $in[$i] : push @out1, $in[$i];
}'
} );
__DATA__
Benchmark: timing 100000 iterations of C-style, push...
C-style: 13 wallclock secs (12.97 usr + 0.00 sys = 12.97 CPU) @ 77
+10.10/s (n=100000)
push: 18 wallclock secs (18.79 usr + 0.00 sys = 18.79 CPU) @ 53
+21.98/s (n=100000)
| Answer: How can I skip an element in an array whilst reading... contributed by perlplexer $|-- ? push @a, $_ : push @b, $_ for @in;
| Answer: How can I skip an element in an array whilst reading... contributed by Russ This looks similar to Can I multiply corresponding numbers in two arrays together?.
Skipping one element can happen with a next in your loop, or just increment the index, if you are using them. |
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|