I wrote a simple function to randomize the order of an array. In
pseudo-code, it looks like this :

def _array_rand (a) :
    for i = 0 to len (a)
        j = rand (len (a))
        temp = a[i]
        a[i] = a[j]
        a[j] = temp
    return(a)

Can anyone tell me if I'm missing the obvious here? Is the algorithm at
fault?

I'm getting a definite bias in the results when the function is written
in PHP (4.2.0 Win) with both rand() and mt_rand(). The same function
written in Python doesn't seem to exhibit the bias.

Sample output:

        Python          PHP
1       1806461 1651056
2       1809213 1717800
3       1804307 1777075
4       1807041 1814477
5       1803453 1845398
6       1808826 1868065
7       1812426 1877706
8       1808599 1869301
9       1811242 1846000
10      1808432 1813122

You can see this curve effect in the script below, which includes a
simple test-harness.

<?
        function _array_rand($a)
        {
                $num = sizeof($a);
                for ($i = 0; $i < $num; $i++)
                {
                        $j = mt_rand (0, $num-1);
                        //$j = rand (0, $num-1);
                        $temp = $a[$i];
                        $a[$i] = $a[$j];
                        $a[$j] = $temp;
                }
                return ($a);
        }

        $a = array(1,5,10,15,20,25,30,35,40,45);
        $r = array(0,0,0,0,0,0,0,0,0,0);

        $iterations = 80000;

        for ($i = 0; $i < $iterations; $i++) {
                $b = _array_rand($a);
                for ($j = 0; $j < sizeof($r); $j++) {
                        $r[$j] = $r[$j] + $b[$j];
                }
        }

        echo('<table border="0">');
        for ($i = 0; $i < sizeof($r); $i++) {
                echo("<tr><td>" . ($i+1) . "</td><td>" . $r[$i] . "</td>\n");
                $x = ($r[$i]/($iterations/20))-100;
                echo('<td><img
src="http://psc.apl.washington.edu/northpole/pngs/Bluebar_r8_c1.gif";
height="10" width="'.$x.'"></td></tr>');
        }
        echo('</table>');
?>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to