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

Re^2: getting random number 8 times never the same

by JavaFan (Canon)
on Oct 31, 2010 at 22:21 UTC ( [id://868644]=note: print w/replies, xml ) Need Help??


in reply to Re: getting random number 8 times never the same
in thread getting random number 8 times never the same

For long lists, that isn't more efficient than shuffling. Shuffling means going through the list once, swapping each element. Splicing means going through (on average) half the list in each iteration moving the element one to the left.

Splicing a random element out of an array takes on average linear time.

  • Comment on Re^2: getting random number 8 times never the same

Replies are listed 'Best First'.
Re^3: getting random number 8 times never the same
by BrowserUk (Patriarch) on Oct 31, 2010 at 22:46 UTC
    For long lists, that isn't more efficient than shuffling.

    Regardless of the length of the list, which is quicker depends upon the ratio of picks.

    ...for a small number of picks, Ie. If the ratio of picks to list size is less than ~15%, spliceing is quicker than shuffling the whole list:

    #! perl -slw use strict; use List::Util qw[ shuffle ]; use Benchmark qw[ cmpthese ]; our $N //= 20; our $S //= 8; our @nums = 0 .. $N; cmpthese -1, { shuffle => q[ my @s = ( shuffle @nums )[ 0 .. $S-1 ]; ], splice => q[ my @s = map splice( @nums, rand( @nums ), 1 ), 1 .. $ +S; ], }; __END__ c:\test>868601 -N=10 -S=2 Rate shuffle splice shuffle 894654/s -- -10% splice 993686/s 11% -- c:\test>868601 -N=10 -S=3 Rate splice shuffle splice 769417/s -- -9% shuffle 844675/s 10% -- c:\test>868601 -N=100 -S=15 Rate shuffle splice shuffle 196571/s -- -5% splice 207873/s 6% -- c:\test>868601 -N=100 -S=17 Rate splice shuffle splice 186995/s -- -3% shuffle 192359/s 3% -- c:\test>868601 -N=1000 -S=169 Rate shuffle splice shuffle 19552/s -- -2% splice 19968/s 2% -- c:\test>868601 -N=1000 -S=170 Rate splice shuffle splice 20274/s -- -1% shuffle 20569/s 1% -- c:\test>868601 -N=10000 -S=1998 Rate shuffle splice shuffle 1578/s -- -6% splice 1674/s 6% -- c:\test>868601 -N=10000 -S=1999 Rate splice shuffle splice 1601/s -- -1% shuffle 1625/s 2% --

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

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

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

    No recent polls found