Yet another question about random numbers
mhedges
Raised on VCSMember Posts: 634
Hello -
Trying to look for a simple way to generate two random numbers which should not be equal to each other (and without using tables), I created two attributes, Random1 and Random2, and wrote the following code:
Actor Event Handler:
- Change attribute Random1 to 0
Change attribute Random2 to 0
Loop Until Random1 =/= Random2:
- Change attribute Random1 to random(1,3)
- Change attribute Random2 to random(1,3)
Then Actor1 and Actor2 display Random1 and Random2.
After running, there are instances where Random1 was in fact equal to Random2.
What the heck is up?
Thanks, regards.
Comments
forgive me if this isn't 100% correct, but i think i worked this out a few years ago, this is from memory. The logic should work, I have an extra attribute used to trigger the function, but the rest should make sense.
if getRandom=true
change attribute Random1 to Random(1,3)
change attribute Random2 to Random(1,3)
Send and Receive Data using your own Server Tutorial! | Vote for A Long Way Home on Steam Greenlight! | Ten Years Left
@jonmulcahy , yes, I have another actor to click and change a boolean to true which starts the process perilously described, the the boolean is changed to false again.
The reason why I used Loop is that:
if random1 = random2
change attribute random2 to random(1,3)
could generate yet another random1=random2.
Any other ideas (other than cheating myself for forcing random2 to be random1+1 in case of a match)?
My Blog / App Store / Google Play
OK, I guess I fixed it by inserting a timer. Here's the code for the event handler:
If ShuffleOn = true then
Change attribute Random1 to 0
Change attribute Random2 to 0
If Random1 = Random2:
Loop While Random1 = Random2
Change attribute Random1 to random(1,3)
Change attribute Random2 to random(1,3)
End If
Timer:
After 0.05 seconds
ShuffleOn = false
End If
It works, but I'm somewhat disappointed I had to insert the timer; I thought the Loop would take care of it just fine.
My Blog / App Store / Google Play
See this thread: http://forums.gamesalad.com/discussion/68841/random-numbers-no-repeating.
New to GameSalad? (FAQs) | Tutorials | Templates | Greenleaf Games | Educator & Certified GameSalad User
Sorry, @tatiang, I fixed the title of the thread, as I actually was referring to two random numbers which should not be equal to each other. I read the thread you included above about five to ten minutes ago, though, looking for an answer. Thanks for your concern!
My Blog / App Store / Google Play
I'd dump the loops and timers and rules and just use something like this:
Change R1 to random(1,3)
Change R2 to (R1-1+random(1,2))%3+1
The suggestion @tatiang made will still work. It will look like this:
The above algorithm will always return two random numbers between 1 and 3 but they will never be the same. (And it will be blazingly fast and efficient!)