Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^5: Switch the odd/even elements of an array

by johngg (Canon)
on Mar 06, 2011 at 17:37 UTC ( [id://891695]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Switch the odd/even elements of an array
in thread Switch the odd/even elements of an array

I've always steered clear of using prototypes but I thought I'd have a go with them to see if I could come up with a general routine a bit like List::MoreUtils::natatime() but taking a code block rather than returning an iterator. This is what I came up with, putting a prototype declaration at the top of the script and fleshing out the subroutine later.

... sub groupsOf (&$@); ... sub groupsOf (&$@) { my $rcToRun = shift; my $groupsOf = shift; my $rcDoIt; $rcDoIt = sub { $rcToRun->( map shift, 1 .. min scalar( @_ ), $groupsOf ), @_ ? &$rcDoIt : (); }; &$rcDoIt; } ...

It seems to do the right thing. With regard to rotating the elements of an array, I would have thought the push @array, shift @array for 1 .. $n; idiom was easier to understand but others may disagree. Here is sub groupsOf() in action.

use strict; use warnings; use feature qw{ say }; use List::Util qw{ min }; sub groupsOf (&$@); my @arr = ( 1 .. 20 ); say qq{@arr}; my @twos = groupsOf { reverse @_ } 2, @arr; say qq{@twos}; my @threes = groupsOf { reverse @_ } 3, @arr; say qq{@threes}; say q{-} x 40; my @rot1 = groupsOf { rotateFromFront( 2, @_ ) } 5, @arr; say qq{@rot1}; my @rot2 = groupsOf { rotateFromBack( 2, @_ ) } 5, @arr; say qq{@rot2}; say q{-} x 40; my @sums = groupsOf { my $sum; $sum += $_ for @_; $sum } 6, @arr; say qq{@sums}; sub groupsOf (&$@) { my $rcToRun = shift; my $groupsOf = shift; my $rcDoIt; $rcDoIt = sub { $rcToRun->( map shift, 1 .. min scalar( @_ ), $groupsOf ), @_ ? &$rcDoIt : (); }; &$rcDoIt; } sub rotateFromBack { my( $places, @arr ) = @_; unshift @arr, pop @arr for 1 .. $places; return @arr; } sub rotateFromFront { my( $places, @arr ) = @_; push @arr, shift @arr for 1 .. $places; return @arr; }

The output.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2 1 4 3 6 5 8 7 10 9 12 11 14 13 16 15 18 17 20 19 3 2 1 6 5 4 9 8 7 12 11 10 15 14 13 18 17 16 20 19 ---------------------------------------- 3 4 5 1 2 8 9 10 6 7 13 14 15 11 12 18 19 20 16 17 4 5 1 2 3 9 10 6 7 8 14 15 11 12 13 19 20 16 17 18 ---------------------------------------- 21 57 93 39

I hope this is of interest.

Cheers,

JohnGG

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-23 10:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found