dimanche 24 avril 2016

rand() in for loop in nawk returns always same value -ksh

i am troubling myself too much time now with this rand().

I want to add 1000 random numbers in an array, this is what i have so far, it works ith no error, but rand assigns all the time the same number in the arrays passing. the vary of the random numbers i want it to be from 1 to 999... any ideas whats going wrong?

btw i am running in ksh...

nawk  ' BEGIN{ 
    for (i=0; i<=999; i++) {
        srand()
        NUMBERS[i]= int(rand()*(999))
        print NUMBERS[i]
    }
}'

P.S. Not a dublicate, no other same question for ksh.

UPDATED

nawk  ' BEGIN{ 
    srand(1)
    for (i=0; i<=999; i++) {
        NUMBERS[i]= int(rand()*(999))
        XNUMBERS[i]= int(rand()*(999))
        print NUMBERS[i]
        print XNUMBERS[i]
    }
}'

UPDATE_2

So the working code i have is this

NUMBERS=`nawk ' BEGIN{ 
    srand()
    for (i=0; i<=999; i++) {
        printf("%s\n", 100 + int(rand() * (899)));
    }   
}'`
NUMBERS
#echo $NUMBERS
XNUMBERS=`nawk ' BEGIN{ 
    srand()
    for (i=0; i<=999; i++) {
        XNUMBERS[i]= 100 + int(rand() * (899));
    }
    for (i=0; i<=999; i++) {
        ver=XNUMBERS[i] "";
                rev = "";
        for (q=length(ver); q!=0; q--) {
                rev = rev substr(ver, q, 1);
               }
        printf("%s\n", XNUMBERS[i] "|" rev );
    }
}'`

i am creating two different lists, but the rand() is giving in both the same exact numbers in the same position.... how can i make the second rand give different numbers?????

Final Update

Sooooo, to any people reading and have the same problem, the solution is to ue a sleep 1 between the two parts that you call the srand....




Aucun commentaire:

Enregistrer un commentaire