Generating random numbers

Hi,

I am having trouble with generating random numbers. can this be done with awk?

So I have a file that looks like this:

23 30
24 40
26 34

So column1 is start and column2 is end. I want to generate 3 random #'s between start and stop:

So the output will look like this:

23 30 26 28 29
24 40 24 28 38
26 34 28 30 31

where the last 3 columns are random numbers. Is this possible?

thanks:confused:

use $RANDOM and appropriate MOD function.

does the $RANDOM function work for awk?

Use -v construct of awk, to read the shell variable into awk processing

Hi,

Please try the below if you are looking for solution in Perl,

while(<DATA>){
srand();
my ($start, $end) = split(/\s/,$_);
my $arr = [$start..$end];
push (my @result,$start,$end);
for(1..3){
push(@result, $arr->[rand(scalar(@$arr))]);
}
print "@result\n";
}
__END__
23 30
24 40
26 34

you can play around with this awk code.

srand();
r=int(((rand() *(1+MAX-MIN))+MIN));
#!/bin/ksh
# or bash
cat file | while read a b
do
        echo -n "$a $b"
        ((max=b-a))
        ((n=RANDOM % max + a))
        echo -n " $n"
        ((n=RANDOM % max + a))
        echo -n " $n"
        ((n=RANDOM % max + a))
        echo " $n"
done

You can use shell services also in awk like - not so good as use rand. Shell using = lot of overheading:

     # define cmd
     cmd="echo $RANDOM"
     cmd | getline  random
     # close pipe
     close(cmd)

Here is the mini game i created named "Guessing Game"

#!/usr/bin/awk -f
BEGIN {
    srand();
    MIN=1;
    MAX=50;
    NUM=0;
    TRY=5;
    COUNT=1;
    r=int(((rand() *(1+MAX-MIN))+MIN));
    print "Please pick a number between 1-50"
    while (r != NUM) {
    getline NUM < "-"
        if (r < NUM) {
                print "Lower!"
        } else if (r > NUM) {
                print "Higher!"
        } else {
            print "Congratulations! You got the right number!\n"
            exit;
        }

        if (COUNT == 5 && r != NUM) {
                print "Sorry! Better Luck Next Time!"
                print "The correct number is number " r;
                exit;
        }
        COUNT++;
    }
}

---------- Post updated at 06:13 PM ---------- Previous update was at 05:30 PM ----------

try.. (usage:scriptname file)

#!/usr/bin/awk -f
{
srand();
MIN=$1;
MAX=$2;
NUM=3;

count=0
while (count < NUM) {
        array[count]=int(((rand() *(1+MAX-MIN))+MIN));
        count++;
        }

print MIN,MAX,array[0],array[1],array[2];

thanks for the replies but I still have trouble getting a random # set. I am most familiar with awk.. its great that there are examples that dont use awk but it would be great to show an example. sorry and thanks

didnt i post already what you want?? :S or you could at least played a little on my code.

#!/usr/bin/awk -f
{
srand();
MIN=$1;
MAX=$2;
NUM=3;

count=0
while (count < NUM) {
        array[count]=int(((rand() *(1+MAX-MIN))+MIN));
        count++;
        }

print MIN,MAX,array[0],array[1],array[2];