How do I make unique random numbers?

0 favourites
  • 7 posts
From the Asset Store
Easily generate many levels from a set of pre-built scenes (Construct 3 template)
  • I want to set a value to a random whole number but I do not want it to repeat the same number unless it has given 2 different numbers before it.

    example: Lets say I want to get a random number 1-4 each time I push a button it will random a number between those values.

    lets say it gives me 1 now I do not want to get 1 the next time 2x I push the button, but after that I want 1 to go back into the pool of random numbers

    so the out of a string of 4 times I random the number I wont ever get

    1,1,1,1

    1,1,4,1

    1,2,1,2

    1,2,3,2

    etc...

    combinations I would get would be

    1,2,3,4

    1,2,4,1

    1,4,2,3

    2,4,3,1

    etc...

    I know a array could do something like this but I am unsure how to set it up

    anyone have any ideas?

  • The following should work. You just keep track of the previous two numbers and do a bit of a trick to ensure only a number not used the previous two times is used. The start of layout stuff is to initialize it with two different random numbers.

    Global number rand=0

    Global number prev1=0

    Global number prev2=0

    Start of layout

    --- set rand to int(random(4))+1

    --- set prev1 to (rand-1)%4+1

    On key pressed

    --- set prev2 to prev1

    --- set prev1 to rand

    --- set rand to int(random(4-2))+1

    ------ compare rand >= prev1

    --------- add 1 to rand

    ------compare rand>=prev2

    --------- add 1 to rand

  • It seems this can give unwanted results in cases where prev2 < prev1. For example row 1,2,2 or 2,3,3 is possible.

    Also the initializing row "set prev1 to (rand-1)%4+1" always sets prev1 to rand.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Good catches. It wasn't fully tested. That -1 shouldn't be there. And the other issue should be fixable with min() and max().

  • R0j0 I understand all of your and have a idea how to put it into C2, expect for this line "set prev1 to (rand-1)%4+1"

    I do not fully understand what it does and I am not sure what the % is doing

  • % (modulo, remainder after division)

  • Here's a capx with it working:

    https://dl.dropboxusercontent.com/u/542 ... peat2.capx

    The expression (rand-1)%4+1 was actually a typo, I wanted rand%4+1.

    What it does is give the next number after rand or 1 if rand was 4.

    1 -> 2

    2 -> 3

    3 -> 4

    4 -> 1

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)