bjornand@idt.unit.no (Bjoern Andersen) (05/18/89)
I need to pick a word from a list in a random sequence. How do I achieve that in a csh or sh script? -- Bjoern.
kamat@uceng.UC.EDU (Govind N. Kamat) (05/19/89)
In article <19669@adm.BRL.MIL> bjornand@idt.unit.no (Bjoern Andersen) writes: > >I need to pick a word from a list in a random sequence. How do I >achieve that in a csh or sh script? ksh has a variable called RANDOM, which returns a random value each time it is accessed. sh has no equivalent; I don't know about csh. You could always write a C program to call rand(). -- Govind N. Kamat College of Engineering kamat@uceng.UC.EDU University of Cincinnati Cincinnati, OH 45221, USA
decot@hpisod2.HP.COM (Dave Decot) (05/20/89)
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);
}
bph@buengc.BU.EDU (Blair P. Houghton) (05/20/89)
In article <19669@adm.BRL.MIL> bjornand@idt.unit.no (Bjoern Andersen) writes: > >I need to pick a word from a list in a random sequence. How do I >achieve that in a csh or sh script? > >-- Bjoern. In the Unix archives at j.cc.purdue.edu, ( anonymous ftp to it, use 128.210.9.2 if necessary...) in the comp.unix.sources/volume2 directory, is a PD program called 'choose'. Snarf it, compile it, and try it. It selects random lines from a file, but the least you can do is rearrange its innards to select random words from a whitespace-separated set of words... --Blair
jes@mbio.med.upenn.edu (Joe Smith) (05/20/89)
At the risk of starting a 'lets all write this in our favorite langauge' blitz, here's an awk (sorry, 'new' awk or GNU awk) function that print's an argument at random. It's easily modified to read a file of words, if you need that. ------------------------------>8 cut here 8<------------------------------ #!/bin/sh gawk ' BEGIN { srand() # set rand() seed from current time print rword(ARGV, ARGC) exit } function rword (a, n) { return a[ int(rand() * n + 1) ] # 1 <= n <= ARGC }' $* -- Joe Smith University of Pennsylvania jes@mbio.med.upenn.edu Dept. of Biochemistry and Biophysics (215) 898-8348 Philadelphia, PA 19104-6059