Random Fun

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

Post Reply
RossG
Posts: 247
Joined: Thu Jan 08, 2015 7:38 am

Random Fun

Post by RossG » Fri May 06, 2016 2:36 pm

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.
Is age an excuse? Eighty-four and counting.
Programming powered by coffee.

dunbarx
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 10331
Joined: Wed May 06, 2009 2:28 pm

Re: Random Fun

Post by dunbarx » Fri May 06, 2016 3:15 pm

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

Da_Elf
Posts: 311
Joined: Sun Apr 27, 2014 2:45 am

Re: Random Fun

Post by Da_Elf » Fri May 06, 2016 6:03 pm

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

RossG
Posts: 247
Joined: Thu Jan 08, 2015 7:38 am

Re: Random Fun

Post by RossG » Fri May 06, 2016 6:11 pm

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.
Is age an excuse? Eighty-four and counting.
Programming powered by coffee.

dunbarx
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 10331
Joined: Wed May 06, 2009 2:28 pm

Re: Random Fun

Post by dunbarx » Fri May 06, 2016 8:23 pm

I forgive me.

Craig

RossG
Posts: 247
Joined: Thu Jan 08, 2015 7:38 am

Re: Random Fun

Post by RossG » Fri May 06, 2016 8:32 pm

So do I.
So do I.

(Had to say it twice to get min. characters.)
Is age an excuse? Eighty-four and counting.
Programming powered by coffee.

Post Reply