question about manipulating an array

Started by Aquilo, October 23, 2003, 05:20:27 PM

Previous topic - Next topic

Aquilo

I need to find a cleaner way to randomly truncate an array to 20 keys from a few hundered this works but runs at like .300+ seconds, could anyone offer a better way to do this?

<?php
$f = file_get_contents('words.txt');
$exp = explode('|', $f);
$arr = array_unique($exp);

   while (count($arr) > 20)
   {
      range(1, count($arr)-1);
      srand((float)microtime()*1010101975);
      shuffle($arr);
      array_pop($arr);
   }

   while (list ($key, $val) = each($arr))
   {
      echo $val,',';
   }
?>

Thanks for any feedback!

[Unknown]

Why not just pick 20 random elements?

-[Unknown]

Iridium

You could shuffle then take the first 20 items (taking random 20 makes no difference).

I would also like to point out that the pseudo-random number generator should be seeded once (and as of PHP 4.2.0, doesn't need seeding at all)

Seeding multiple times often results in surprisingly un-random values (I don't know why this occurs, but there's a lot of pseudo-random number generating theory behind it).

Anguz

#3
yeah, like they said, you could do something like

<?php
$arr1
= explode('|', file_get_contents('words.txt'));
$arr1 = shuffle(array_unique($arr1));

for(
$i = 0; $i < 20; $i++)
    $arr2[] = $arr1[$i];

$str = '';
foreach(
$arr2 as $a)
    $str .= $a . ', ';
echo
$str;
?>


I don't know how fast it'd be though

if you're using ob, I think the echo part'd be faster as

<?php
foreach($arr2 as $a)
   echo
$a,', ';
?>
Cristián Lávaque http://cristianlavaque.com

Advertisement: