Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Golf/Perlish solution to this problem?

by johngg (Canon)
on Jan 31, 2008 at 10:49 UTC ( #665319=note: print w/replies, xml ) Need Help??


in reply to Golf/Perlish solution to this problem?

This solution is non-destructive and uses an array slice rather than push'ing, pop'ing and shift'ing.

use strict; use warnings; my @array = qw{ ace big cat dog egg fig gog hog }; my @newArray = @array[ reOrder( scalar @array ) ]; print qq{@newArray\n}; sub reOrder { my $length = shift; die qq{Array length not a multiple of 4\n} if $length % 4; my $low = 0; my $high = $length - 1; return map { $_ % 2 ? ( $high --, $low ++) : ( $low ++, $high --) } 1 .. $length / 2; }

The output.

hog ace big gog fig cat dog egg

Cheers,

JohnGG

Update: Re-factored subroutine to handle any length of array.

sub reOrder { my $length = shift; my $low = 0; my $high = $length - 1; my @slice = map { $_ % 2 ? ( $high --, $low ++) : ( $low ++, $high --) } 1 .. $length / 2; return @slice, $low == $high ? $low : (); }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2021-01-18 11:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?