General Community > Scripting Help
question about manipulating an array
(1/1)
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:
yeah, like they said, you could do something like
--- Code: ---<?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;
?>
--- End code ---
I don't know how fast it'd be though
if you're using ob, I think the echo part'd be faster as
--- Code: ---<?php
foreach($arr2 as $a)
echo $a,', ';
?>
--- End code ---
Navigation
[0] Message Index
Go to full version