Forum Moderators: coopster

Message Too Old, No Replies

Random Results

or should I say expected results in a random order

         

daisho

2:40 am on Sep 26, 2003 (gmt 0)

10+ Year Member



Hey All,

I have the need to get results from a database in a random order ie:

select * from tbllisting order by random(id);

ofcourse that doesn't work so I figure I have to do it at a PHP level but I can't figure out how to do it easliy and efficiantly.

what I need to do is generate a sequence of random numbers between 0 and x x amount of times without repeating any number.

I first though of doing something like:

<?
$x=10;
$count=0;

for($i=0;$i<=$x;$i++)
$order[$i]=-1;

while( $count<=$x ) {
$tmp=rand(0,$x);
if( -1==$order[$tmp] ) {
$order[$tmp]=$count;
$count++;
}
}
?>

You would set $x to the highest index.

The issue is performance. The probability of hitting 0 or $x is much less than numbers in the center so there ends up being lots of wasted cycles and time.

Any ideas on a better solution?

daisho.

jatar_k

2:48 am on Sep 26, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



what about using array_rand or shuffle and then using push and pop it off the end of the array.

how many elements in the array? are we talking possibly huge?

just off the top of my head

daisho

3:00 am on Sep 26, 2003 (gmt 0)

10+ Year Member



Hey jatar_k,

For this purpose I think it will work. Should only be 20 or 30 items max.

daisho.

jatar_k

3:08 am on Sep 26, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



if it will be that small it will work but if you had to sort anything large it may be a little too heavy.