Pick a random number without repeating the last number chosen

ArmellineArmelline Member, PRO Posts: 5,369

Okay, so I had to generate a random number between 1 and x, without repeating the number chosen the previous time.

The method I learned yonks ago was tshirtbooth's as outlined in this video. This method requires a timer constantly firing, though, and three attributes. I don't like the idea of a timer constantly firing, so I wanted to use a different method.

I don't know if what I'm about to suggest has been put forward before, but a cursory search of the forums didn't reveal it. Essentially I'm wanting to know if I've overlooked something obvious. It seems valid to me, but it's 2.43am...

The method in the video above, of doing random(1,x) and then checking constantly if random = last random, and picking a new number if so, seems to have the potential (in theory) of getting stuck - if the same number is picked in a row enough times, there will be a pause as GameSalad constantly generates new random numbers, waiting for one that isn't the same as the last different one.

How about instead we do

self.Number to random(1,x-1)

So if we're picking from 6 numbers, we'd do

self.Number to random(1,5)

If the last number chosen was 4, this time valid new numbers are 1,2,3,5,6. If we do random(1,5), we're getting 5 potential new numbers. If the new number is 1,2,3,5, we have no problem. It's a new number and we can move on. If it's 4, we're repeating the last number. But 4 isn't representing 4 any more, it's representing 6. So if 4 is picked, we change self.Number to 6.

If the previous number picked was 6, then doing random(1,5) can only result in a new number.

Does that make sense? I'm attaching an image of the logic below.

Sign In or Register to comment.