Page 1 of 1

The shuffle() function is really misbehaving.

Posted: Thu Jul 31, 2003 6:18 pm
by mgelinas
From what I see, the shuffle() function is really misbehaving. In attempting to figure out how it works, I came up with the following code. The shuffling is quite deficient in my development environment: PHP 4.2.0, Apache 1.3.24 and Windows 2000 (all patches applied). Would you mind trying the same code in your environment and let the forum (and me) know if you get real shuffling? Thanks.

Code: Select all

<?php

$sorted_array = range(A,J);
echo "<b>Reference array: </b>";
print_r($sorted_array);
echo "<hr>";

// First loop, no seeding of randomizer, single shuffling
$shuffled = $sorted_array;
for ($i=0; $i<5; $i++)
{
	echo "<b>Shuffled array $i: </b>";
	shuffle($shuffled);
	print_r($shuffled);
	echo "<br>";
}
echo "<hr>";

// Second loop, with seeding of randomizer, single shuffling
$shuffled = $sorted_array;
for ($i=5; $i<10; $i++)
{
	echo "<b>Shuffled array $i: </b>";
  srand((float)microtime()*1000000);
	shuffle($shuffled);
	print_r($shuffled);
	echo "<br>";
}
echo "<hr>";

// Third loop, no seeding of randomizer, numerous shuffling
$shuffled = $sorted_array;
for ($i=10; $i<15; $i++)
{
	echo "<b>Shuffled array $i: </b>";
  for ($s=0; $s<$i+1; $s++)
		shuffle($shuffled);
	print_r($shuffled);
	echo "<br>";
}
echo "<hr>";

// Fourth loop, with seeding of randomizer, numerous shuffling
$shuffled = $sorted_array;
for ($i=15; $i<20; $i++)
{
	echo "<b>Shuffled array $i: </b>";
  for ($s=0; $s<$i+1; $s++)
  {
		srand((float)microtime()*1000000);
		shuffle($shuffled);
  }
	print_r($shuffled);
	echo "<br>";
}
echo "<hr>";

// Fifth loop, no seeding of randomizer, multiple shuffling
$shuffled = $sorted_array;
for ($i=20; $i<25; $i++)
{
	echo "<b>Shuffled array $i: </b>";
  for ($s=0; $s<$i*5; $s++)
		shuffle($shuffled);
	print_r($shuffled);
	echo "<br>";
}
echo "<hr>";

// Sixth loop, with seeding of randomizer, multiple shuffling
$shuffled = $sorted_array;
for ($i=20; $i<25; $i++)
{
	echo "<b>Shuffled array $i: </b>";
  for ($s=0; $s<$i*5; $s++)
  {
		srand((float)microtime()*1000000);
		shuffle($shuffled);
  }
	print_r($shuffled);
	echo "<br>";
}
echo "<hr>";

?>

?>

Posted: Thu Jul 31, 2003 6:40 pm
by RFairey
In what way is it misbehaving?
The output under PHP 4.1.2, As an apache module under Linux is as follows:
http://www.srcf.ucam.org/~rmf33/shuff.php

Posted: Thu Jul 31, 2003 6:45 pm
by Stoker
why start a new thread?

Des rand() and mt_rand() give true random stuff?