Viewed   56 times

Does anyone know what's the randomness of PHP's shuffle() function? Does it depend on the operating system? Does it use PHP's own seeder?

Is it possible to use mt_rand() as generator?



shuffle() function is based on the same generator as rand(), which is the system generator based on linear congruential algorithm. This is a fast generator, but with more or less randomness. Since PHP 4.2.0, the random generator is seeded automatically, but you can use srand() function to seed it if you want.

mtrand() is based on Mersenne Twister algorithm, which is one of the best pseudo-random algorithms available. To shuffle an array using that generator, you'd need to write you own shuffle function. You can look for example at Fisher-Yates algorithm. Writing you own shuffle function will yield to better randomness, but will be slower than the builtin shuffle function.

Friday, October 7, 2022

Its better to use an array to achieve this.

$options = array(
  'Option One',
  'Option Two',
  'Option Three',
  'Option Four'
//Shuffle the array

You can access the options like this (The order will be random);

Sunday, August 21, 2022

Shuffle it with shuffle():


Searching Google for php shuffle array will give you tons of results as well, by the way.

Friday, September 9, 2022

Given numbers between 1 and 100.

  • 9 have 1 digit (1-9)
  • 90 have 2 digits (10-99)
  • 1 has 3 digits (100)

Given numbers between 1 and 1000.

  • 9 have 1 digit
  • 90 have 2 digits
  • 900 have 3 digits
  • 1 has 4 digits

and so on.

So if you select some at random, then that vast majority of selected numbers will have the same number of digits, because the vast majority of possible values have the same number of digits.

Saturday, August 27, 2022

Math.random() is based on java.util.Random, which is based on a linear congruential generator. That means its randomness is not perfect, but good enough for most tasks, and it sounds like it should be sufficient for your task.

However, it sounds like you're using the double return value of Math.random() to choose between a fixed number of choices, which may further degrade the quality of the randomness. It would be better to use java.util.Random.nextInt() - just be sure to reuse the same Random object.

Sometimes, it doesn't appear so random by looking at a snapshot on a resource pool to see which pieces it's getting at that instant

Our brains are really good at spotting patterns in perfect randomness, so that means almost nothing.

Tuesday, October 25, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :