Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Processing arrays 2 elements at a time (TIMTOWTDI)

by dimmesdale (Friar)
on Aug 02, 2002 at 15:44 UTC ( [id://187130]=note: print w/replies, xml ) Need Help??


in reply to Processing arrays 2 elements at a time (TIMTOWTDI)

Well, having required something like this recently, I feel obliged to comment.

I particurly liked merlyn's solution:

@copy = @$r; while (my @pair = splice @copy, 0, 2) { push @$r2, [@pair]; }

However, I'll modify it slightly to show everyone what I came up with. (Maybe it's just me, but bit-wise operators always seem to pop-up in my code ... probably where they shouldn't :)

@copy = @$r; # I guess you know that your array will work for this, but # it may be desirable to check (especially for n-'tuples') # that the array is divisible by 2 (or n). I guess that # depending on what you're expecting this can be done on a # all or nothing basis, or inside the loop while (0..$#copy) { next if $_&1; # this skips all odds (you used a mod in # your original I think). To expand to more # 'tuples', you'd have to change this to # next if $_%n push @$r2, [$copy[$_],$copy[$_+1]]; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://187130]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-19 17:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found