[UFO Chicago] Re: PHP Programming Problem

Nate Riffe inkblot@geocities.com
Mon, 27 Aug 2001 01:07:41 -0500 (CDT)


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, 26 Aug 2001, Nate Riffe wrote:

> No files specified.  Using stdin.
>
> Opening file "stdout" type text.
> Hey UFO,
>
> I've got a problem in need of a solution.  I need to write a function in
> PHP that will quickly and efficiently read a random line from a text file
> that is close to 50K lines long.  Just one line, at random.  It needs to
> be fast because it will get called about 300 times per page load.  Any
> takers?
>
> -Nate

Ok, I found a solution.  For future reference, to pick a random word from
/usr/share/dict/words in a VERY SHORT amount of time, paste this code
into your PHP script and call random_word():

$words_file = fopen("/usr/share/dict/words","r");
$words_length = filesize("/usr/share/dict/words");

function random_word() {
  global $words_file, $words_length;
  $rand_offset = rand(0,$words_length - $words_length % 1024);
  fseek($words_file, $rand_offset - $rand_offset % 1024, SEEK_SET);
  $words = explode("\n", fread($words_file, 1024));
  $rand_word = $words[rand(1, count($words) - 1)];
  return trim($rand_word);
}

I got it to generate 3000 random words in under a second.

- -Nate

>
> ------------------------------------------------((\))<----------------------
> Nate Riffe                 | PGP public key available at:
> http://movealong.dhs.org/  | http://movealong.dhs.org/~inkblot/pgp-key.asc
> inkblot@geocities.com      |
> nriffe@students.depaul.edu | Secure your email today!
> Good signature made 2001-08-26 20:10 GMT by key:
>   1024 bits, Key ID 87019478, Created 2000-11-09
>    "Nate Riffe <inkblot@geocities.com>"
> Opening file "/dev/null" type text.
>

- -- 
- ------------------------------------------------((\))<----------------------
Nate Riffe                 | PGP public key available at:
http://movealong.dhs.org/  | http://movealong.dhs.org/~inkblot/pgp-key.asc
inkblot@geocities.com      |
nriffe@students.depaul.edu | Secure your email today!

-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 5.0i for non-commercial use
Charset: noconv

iQA/AwUBO4njr4jJNqeHAZR4EQIhHACg8VNwRpPF7/PvpdBXSBEhPVcjbggAnit9
MYELZgNRnA96fpvuFrnix7W1
=quBj
-----END PGP SIGNATURE-----