The shuffle() function is really misbehaving.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mgelinas
Forum Newbie
Posts: 13
Joined: Tue Jun 10, 2003 6:33 am
Location: QC Canada

The shuffle() function is really misbehaving.

Post 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>";

?>

?>
RFairey
Forum Commoner
Posts: 52
Joined: Fri Jun 06, 2003 5:23 pm

Post 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
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

why start a new thread?

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