ruby - Why would I want to use a custom RNG for Array#shuffle? -


the documentation array#shuffle states:

shuffle(random: rng) → new_ary

the optional rng argument used random number generator.

a.shuffle(random: random.new(1))  #=> [1, 3, 2] 

what mean , why want that?

internally array#shuffle method needs source of random numbers. when provide optional rng parameter, telling method use object data source.

it not directly reproducibility. default .shuffle uses shared kernel#rand rng , can seeded using srand.

you can reproduce shuffles follows:

srand(30) [0,1,2,3,4,5,6].shuffle # => [3, 1, 2, 0, 4, 6, 5]  srand(30) [0,1,2,3,4,5,6].shuffle # => [3, 1, 2, 0, 4, 6, 5] 

if need repeatability tests, srand cover needs.

so is for?

shuffling array requires source of random numbers in order work. allowing over-ride default kernel#rand, design allows control on how these sourced. other functions require source of randomness allow similar over-rides e.g. array#sample.

having level of control allows build shuffled arrays arbitrarily, , separately other parts of code rely on sources of random numbers. reproducible output 1 useful outcome, addition of independence other parts of program using random numbers may or may not need reproducible results, or may run @ different times cannot control.

in addition, shuffling algorithms there a problem creating distribution when have long list. if shuffling n items need factorial(n) or n! possible unique lists of numbers come rng, otherwise cannot possibly produce allowed arrangements. ruby's built in rng, limit occurs when shuffling around 2000 items in theory - provided srand value has been chosen high quality original random source. can better using rng has has higher limit, or "true" rng sources data physical system.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -