Randomize Array

  • I'm trying to create an array with one particular element, and 3 other random elements. There's some checking for duplicates that I'm not doing right, but I haven't been able to debug it. If you refresh the page enough times, some elements will be duplicates. Any suggestions on making this process faster, shorter, better algorithm, etc. would also be appreciated. Thanks in advance, and God bless

    http://db.tt/aF4lluvw

  • Hey tnewhook,

    You might wanna check out a third party plugin developed by joe7 called random array, I think it will do what you need it to do. I use it on several of my games and it works great. Here's a link:

    scirra.com/forum/plugin-randomarray_topic45277.html

    cheers

  • As of C2 Release 87 there are two features that make this easy: While loop and a feature to test if a value is in the array. This isn't your example, but I think it does what you were asking about. Tries shown are the number of times a random number was generated. If it is bigger than the array width, then there were duplicates among the numbers generated, and so a new random number was generated.

    RandomArrayNoDuplicates.capx

  • Thanks guys (and girls) - I really appreciate it.

    @kittiewan - that was just what I needed - much more elegant than my solution. I didn't know I could compare a variable to all elements in an array.

    @daveryaaziem - I've seen that plugin, but I can't modify the size of the array at runtime. Thanks, tho :)

  • Try Construct 3

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

    Try Now Construct 3 users don't see these ads
  • kittiewan - As I'm looking at the code again, I had one question: In step 3, you have a test to see if the array already contains that random number. If the test fails, how does the program know how to handle it? Does it simply retry until it can pass the test. I'm not sure how the statement inside is the loop is handled logically.

    Thanks again for your help.

  • Yes, it keeps trying.

    The key is that you only add to the variable i if the random value is not in the array.

    That way, as long as i is less than the desired number of random numbers in the array, it keeps trying.

    The variable Tries isn't really necessary to make it work. It is there just to show you how many times it had to loop to get the desired number of unique values. Say you are trying to generate 4 variables (the width of the array). If Tries=10 that means you had to loop 10 times to get 4 unique values.

  • kittiewan - ya, I figured that out about the tries variable. BTW, your Memory Match Tutorial is great! :)

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