On Fri, 29 Jul 2005 21:07:40 -0400, you wrote:

>Eric Amick wrote:
>> opendir DIRHANDLE, $dirname or die "OOPS! $!";
>> while (my $filename = readdir(DIRHANDLE))  {
>>     # Assuming subdirectories are ignored. Other criteria
>>     # can be added here.
>>     next if -d "$dirname/$filename";
>>     $random_file = "$dirname/$filename" if rand < 1/(++$file_count);
>> }
>Wouldn't this tend to favor files alphabetically last ? It would take 
>quite a few iterations to get the first file alphebetically with this.

The odds of choosing each file are equal; don't forget that the value of
$file_count increases whether the filename is remembered or not, so the
odds of choosing later files *decreases*. 

Consider three files for simplicity. On the first pass, the value of
rand is obviously less than 1, so the first file is chosen, at least for
now. On the second pass, the second file is chosen with odds of 1/2,
which means the first file has a 1/2 chance of still being chosen. On
the third pass, the last file is chosen with odds of 1/3. This means the
second file can be the chosen file with odds of 1/2 (odds it was chosen
previously) x 2/3 (odds third file was *not* chosen) = 1/3. The first
file's chances are, using the same reasoning, 1 x 1/2 x 2/3 = 1/3.

If there's a fourth file, it will be chosen with odds 1/4, and the
others will be chosen with odds 1/3 x 3/4 = 1/4. You get the idea.

-- 
Eric Amick
Columbia, MD

_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to