Page 1 of 1

random() : test if a number does not appear twice

Posted: Tue Jan 05, 2016 1:16 am
by problème
Hello, (Happy new year)
I have a program that randomly selected numbers , then checks whether the number is not already out before, if it is already out , it chose a new number if not we put it in a list. The program ends when all the numbers are out.
My program work correctly with 10 numbers but when i test with 32 numbers, liveCode crash.

Code: Select all

global liste, number
put 10 into number
--put 32 into number
command test2
   if num of items of liste = number then
      answer "End"
   else 
      put random(number) into motRdm   
      --put motRdm & "||||||||||||||" & liste
      if liste contains motRdm  then
         test2
      else
         if liste is empty then
            put motRdm into liste
         else 
            put liste & "," & motRdm into liste
         end if
      end if
   end if
end test2

Re: random() : test if a number does not appear twice

Posted: Tue Jan 05, 2016 5:27 am
by dunbarx
Hi.

Your handler does not work. You do not initialize "liste", Also, NEVER use a word like "number" for a variable. It is reserved in the worst way.

But I think I know what you intended, and the attempt is fine.

But you want to rethink the method. Extracting random numbers until you get a list that does not repeat is likely to need to run for a long time, as you discovered with the "32" you tried. This ought to set off an alarm in your head, that another method should be considered.

This subject is commonly discussed, to randomize, (or to create) a pre-defined list without repeats. Why not look at the thread "Need Random, Non-repeating Images script" in the beginner's forum. I posted a direct step-wise handler of doing one aspect of this task, which you should be able to understand and experiment with. And Jacque posted a more compact and complete handler. Examine both, and play with both, stepping through each.

Do you see the difference? My method limits the number of "passes" through a loop equal to the number of elements of interest. Jacque uses a clever "sort" variant. You do not need to, and surely do not want to, do any more than that.

Please write back with you thoughts...

Craig Newman

Re: random() : test if a number does not appear twice

Posted: Tue Jan 05, 2016 3:14 pm
by Klaus
And, quite important, the initialisation of variables needs to be INSIDE of the handler to work!

Code: Select all

global liste, tNumber
## put 10 into tNumber
command test2
  put 10 into tNumber
  if num of items of liste = tNumber then
...

Re: random() : test if a number does not appear twice

Posted: Wed Jan 06, 2016 2:36 pm
by problème
thanks for the helps