random k-sample of a file
    Russell Lewis 
    webmaster at villagersonline.com
       
    Thu Oct  9 15:58:42 PDT 2008
    
    
  
BEGIN CODE
char[][] choose(int k)
{
   char[][] bufs; bufs.length = k;
   for(int i=0; i<k; i++)
     bufs[i] = ReadALine();
   while(!feof(stdin))
   {
     int i = random(0,k);
     bufs[i] = ReadALine();
   }
   return bufs;
}
END CODE
Andrei Alexandrescu wrote:
> I just ran across a nice little problem that I wanted to share as an 
> exercise for the interested in futile pastimes.
> 
> The challenge, should you accept it, is to write a program that given a 
> number k and a file, outputs k lines picked uniformly at random from the 
> file. (If the file has less than k lines, it should all be output.) The 
> file's size is unbounded so loading it in memory is not an option. How'd 
> you go about it?
> 
> 
> Andrei
    
    
More information about the Digitalmars-d
mailing list