* Ken Weingold ([EMAIL PROTECTED]) wrote:

> I think I remember a while back someone haveing a script to take lines
> randomly from a text file to put into a custom header.  Does anyone
> have this?

Replace \n with \n%\n and run it through strfile.  Then run fortune
over the generated data file.  If you have a lot of lines, this will be
significantly more effecient than a naive implimentation (such as the
read all lines and randomly generate an index to the generated list:
nice brute force method :), and give flexibility to search by regexp,
length, etc.

If you still want to use a script but don't want to eat
<filesize> * <structure overhead> and IO every invocation, you'll want
to seek to somewhere random in the file and read until you get a
complete line, ala (in Ruby):

begin
        File.open(file) do |f|
                f.seek(rand(File.size(file)))
                f.gets
                puts f.gets
        end
rescue EOFError
        retry
end

This will, however, guarantee the first line will never be read, and
choose longer lines over shorter ones.

A better alternative is to index the file first, creating a list of
offsets in the file for each entry in fixed length fields.  The above
technique can then be used effectively, since you can both mod the seek
to record boundaries and know you're not choosing any one entry over any
other.  Then you just shove the offset into a seek on the data file.

Depends how much fun you think you can cope with ;)

-- 
Thomas 'Freaky' Hurst  -  [EMAIL PROTECTED]  -  http://www.aagh.net/
-
Chef, n:
        Any cook who swears in French.

Reply via email to