Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.

Array One-liners

by japhy (Canon)
on Sep 24, 2000 at 11:55 UTC ( #33835=snippet: print w/replies, xml ) Need Help??
Description: Less than 80 characters each! Whoo-hoo!
# randomize, via Fisher-Yates
@array[-$i,$j] = @array[$j,-$i] while $j = rand(@array - $i), ++$i < @

# remove a chunk from the end and place at the beginning ("cutting")
splice @array, 0, 0, splice(@array, rand @array);

# weave an array, method 1 (ABCDEF => ADBECF)
splice @array, @array/2 - $_, 0, pop @array for 0 .. (@array/2)-1;

# weave an array, method 2 (ABCDEF => DAEBFC)
splice @array, @array/2 + $_, 0, shift @array for 0 .. (@array/2)-1;
Replies are listed 'Best First'.
RE: Array One-liners
by merlyn (Sage) on Sep 24, 2000 at 14:44 UTC
    splice @array, 0, 0, splice(@array, rand @array);
    Good stuff, but typically we spell that:
    unshift @array, splice @array, rand @array;
    splice is cool, but you don't need to use it for the common thingies.

    -- Randal L. Schwartz, Perl hacker

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2023-11-29 18:13 GMT
Find Nodes?
    Voting Booth?

    No recent polls found