6.22 Randomizing Lines and Words


You want to randomize every line in a file.

Technique

Load the file into an array of lines, shuffle the array, and then write it back to the file:

 <? $fn = "/usr/home/sterling/random_file.txt"; $reg_array = file ($fn); srand ((double)microtime()*1000000); shuffle ($reg_array); $fp = @fopen($fn, "w") or die("Cannot Open file $fn");     fputs ($fp, implode ("", $reg_array)); @fclose ($fp) or die ("Cannot Close file $fn"); ?> 

Comments

First, we load the file into an array using the file() function. Now that we have an array of lines, we can randomize the array. Next, we seed the random number generator for shuffle() , and then pass the array to shuffle() . (Note that we do not need to assign the return value from shuffle() because it operates on the array directly.) Finally, we open the file again, truncate it to zero, and write the entire array to the file (with randomized lines).

Here is a neat program that randomizes all the words of a particular file and then prints them to the browser:

 <?php $fn = 'somefile.txt'; srand ((double)microtime()*1000000); foreach (file ($fn) as $line) {      $words = preg_split("/\s+/", $line);      shuffle ($words);      $data .= implode(" ", $words) . "\n"; } print $data; ?> 

So, if this program were fed something like the following poem from Robert Frost:

 Gathering Leaves Spades take up leaves No better than spoons, And bags full of leaves Are light as balloons. I make a great noise Of rustling all day Like rabbit and deer Running away. But the mountains I raise Elude my embrace Flowing over my arms And into my face. I may load and unload Again and again Till I fill the whole shed, And what have I then? Next to nothing for weight; And since they grew duller From contact with earth Next to nothing for color. Next to nothing for use. But a crop is a crop, And who's to say where The harvest shall stop? 

It would output:

 Leaves Gathering take Spades leaves  up than No better  spoons, of And full bags leaves light Are balloons. as noise make I a great rustling  Of all day deer Like  rabbit and  away. Running raise I the But mountains Elude my embrace Flowing over arms my my And face.  into may I load and  unload again and  Again I the fill  shed, whole Till  I have what And then? Next weight; to nothing for And grew duller since they contact From with  earth color. Next  to nothing for to  Next for nothing use. a crop is a crop,  But And who's say where to shall harvest The stop? 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net