Page 1 of 1

Random Fun

Posted: Fri May 06, 2016 2:36 pm
by RossG
I want to make a string of 8 unique random numbers.

Code: Select all

repeat with i = 1 to 8
   set itemDel to comma

   put random(36) into tRand
   
   if tRand is not among the items of randTemp then
       put tRand & "," after randTemp
   else
       add 1 to i
   end if
 
end repeat
For reasons which I can't fathom sometimes randTemp has
fewer than eight numbers and sometimes there are repeated
numbers.

Help appreciated.

Re: Random Fun

Posted: Fri May 06, 2016 3:15 pm
by dunbarx
So much fun.

If you limit yourself to 8 passes in your loop, and you get a duplicate, you will not get a new value, eh? So your final list will be short.

The trick (well, there are many) is to take a different tack, where the goal of getting 8 entries is paramount. I would suggest similar code as you already have, but with something like:

Code: Select all

repeat until the number of items of randTemp = 8
Now this might have issues with large samples. Can you see why?

Another way is (pseudo):

Code: Select all

create list of 36 numbers
repeat 8
get a random number based on the number of items in that list
place that item in randTemp
delete that item from the master list
See?

Can you think of other ways?

Craig Newman

Re: Random Fun

Posted: Fri May 06, 2016 6:03 pm
by Da_Elf
due to getting stuck with the exact sequence of numbers for a random generated sequence due to the seed being the same i usually set the seed to the current date and time so its never the same

Re: Random Fun

Posted: Fri May 06, 2016 6:11 pm
by RossG
Craig and Elf.

Shame on you both for not seeing that the line
"add 1 to i"
should have been
"subtract 1 from I".

So I now get 8 items each time and no repeats.

Can't see what caused the repeats though.

Re: Random Fun

Posted: Fri May 06, 2016 8:23 pm
by dunbarx
I forgive me.

Craig

Re: Random Fun

Posted: Fri May 06, 2016 8:32 pm
by RossG
So do I.
So do I.

(Had to say it twice to get min. characters.)