Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

random and unique in range 1

Status
Not open for further replies.

nabana2

Technical User
Sep 26, 2005
21
ZA
Hi

I am trying to create a random 2 digit number for each input record. The same number must also NOT be generated for at least 10 input records. This is what i have tried. I think I am close but I am not sure how to react to duplicates within the 10 record boundry. Probably also a more clever way to do this.

Code:
awk 'BEGIN{srand();x=1}

function chkdig(){
   str = 10 + int(rand() * 90)
		
   for(i=1;i<=10;i++){
   ##problem area##	
      if(arr[i]==str){
         do{
	 str = 10 + int(rand() * 90)
	 }while (arr[i]==str)
      }
   ##this won't check previous records in the array for the new str
   ################
   }
   arr[x] = str
	
   x++
   if(x==11){
   x=1}

   return str
}
{
   print $1, chkdig()
}' inputfile

thanks
 
Hi

My approach :
Code:
function chkdig()
{
  do {
    str = 10 + int(rand() * 90)
    ok = 1
    for (i=1;i<=10;i++) if (arr[i]==str) ok = 0
  } while (!ok)

  arr[x=x%10+1] = str

  return str
}

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top