How do I pick a word at random from a list of words?
Dave Decot
decot at hpisod2.HP.COM
Sat May 20 04:27:14 AEST 1989
Well, this program gives you a random line from a file. The first argument
to the program should be the number of lines in the file.
Compile this program as "select", and use it as:
select `wc -l file` < file
Unfortunately, this only works on systems with gettimeofday(), rand(), and
srand() (such as BSD-derived systems or HP-UX); substitute your local random
number generators and time functions.
Dave Decot
------------------------
#include <stdio.h>
#include <time.h>
main(argc, argv)
int argc;
char *argv[];
{
char s[80];
struct timeval t;
int i, j;
gettimeofday(&t, 0);
j = srand(t.tv_usec);
freopen(argv[2], "r", stdin);
gets(s);
i = rand() % atoi(argv[1]) - 1;
while(i-- > 0)
gets(s);
puts(s);
}
More information about the Comp.unix.questions
mailing list