Translations

Know another language? Translate this tutorial!

Stats

6K visitors
33.5K page views
2,429 translation visitors
3.5K translation page views

Generating Random Numbers Without Duplicates

Favourite 60 favourites
Tutorial written by kittiewanOriginally published on 1st, June 2012 - 11 revisions

Generating unique random numbers is an essential technique for every game maker to know. This short tutorial demonstrates one way to use an array to generate a set of random numbers without duplicates.

The project requires Construct 2 Release 87 or later. The free version is fine.

You can download the complete project here:
http://dl.dropbox.com/u/57899112/RandomNos.capx

The goal is to insert 6 random integers that are greater than or equal to zero, but less than 15, into an array without any duplicates.

1. Create a new project and name it RandomNos.

2. Insert 3 objects into the layout: 2 text objects and an array. Change the objects' properties as shown below:

Name: txtTries
Plugin: Text
Position: 120,64
Size: 200,30

Name: txtValues
Plugin: Text
Position: 124,126
Size: 412,206
Text:

Name: Array
Plugin: Array
Width: 6

Once the objects are inserted your project should look something like this:

Add 2 text objects and an array


3. Switch to the event sheet and add an On start of layout event. Right click on the event and Add a blank sub-event. Your event sheet should look like this:

Add an On start of layout event and a blank sub-event


4. Click on the blank sub-event and right click and choose to Add a local variable as shown in the following figure. (If you don't see add local variable in the popup menu, click on the Events tab and try inserting it from the toolbar. Note that you can only insert a local variable in a place where it makes sense to use one.)

Add a local variable to the On start of layout event


5. The variable will be added above the blank sub-event. Name it randomNumber and accept the defaults. Add two more local variables, i and tries. When you are done the event sheet should look like the following figure:

Insert 3 local variables


6. Modify the blank sub-event by double clicking on it and turning it into a While loop as shown below. Note that to create a while loop you first insert the while condition and then insert the condition that you want to be true.

Change the blank sub-event into a while loop


7. Add some actions to the While loop as shown below. The first action generates a random integer greater than or equal to 0 and less than 15. (Because of the way the Random function works it will not actually generate the upper bound number. You can add 1 to the upper value if you want to include it.) The second action adds to the tries variable which stores the number of attempts made to insert unique random numbers into the array. The third action just displays how many attempts have been made.

Add actions to generate random number and track attempts


8. Select the While event and right click to Add a sub-event with the condition Array Contains randomNumber. Right-click on the condition and Invert it so that actual test is to see that the array does NOT contain the random number.

Add test to see if array does not contain the random number


9. Add some actions to the sub-event that will occur only if the random number is unique among the other numbers already in the array. First, insert the random number into the array at the position i. Then add a line to txtValues to show both i and the random number. Third, add 1 to i since we added a value to the array.

Insert the random number into the array and display it, too.


10. Finally, save and run the project. The result should look like the following figure. Notice that in this case it took eleven attempts to insert 6 random numbers into the array, and also notice that none of the numbers in the right column are duplicates.

The results


That's all there is to it!

NOTES:

1) If you are generating a lot of random numbers there is the possiblity that your While loop could go on for a very, very long time. You may want to add a condition to set a limit to the number of tries as shown in the following figure. For this example it is unlikely you'd ever get close to 1000 tries, but it is a good thing to keep in mind.

limit tries to 1000


2) If you are interested in a bare minimum version of the project, it would involve deleting the two text objects along with their associated events and actions, and it would look like the following figure.

Of course, without the text objects you won't see anything when you run this project.

Bare minimum required


3) The tutorial demonstrates how to generate all of the unique random numbers at once. If you want to generate them one at a time on demand you still use the same basic techniques, but in slightly different ways. To examine a project where a unique random number is generated on click or touch, check out the following project. In addition to realistically implementing a limit on the number of tries, it also shows how to push an element onto the end of an array.

RandomNosPush.capx

Unlock your full gamedev potential

Upgrade to the Personal Edition of Construct 2, it has way more features and won't holding back from making money and using your full creativity like the free edition does. It's a one off payment and all Construct 2 editor updates are free for life!

View deals

Plus, it's got a lot of additional features that will help you save time and make more impressive games!

Congratulations on finishing this tutorial!

Did you learn a lot from it? Share it now with your friends!

Comments

5
Kyatric 71.3k rep

Very nice tutorial as usual.
Thank you a lot !

Saturday, June 02, 2012 at 7:48:27 AM
0
vidi 5,058 rep

Thank you! :)

Sunday, June 03, 2012 at 8:22:55 PM
0
Astro 5,991 rep

Useful indeed

Sunday, June 17, 2012 at 12:36:06 AM
0
kittiewan 12.2k rep

Thanks for encouragement, folks!

Sunday, June 17, 2012 at 8:41:13 PM
0
SocalSam 3,934 rep

Add Subevent has changed. The easiest way to explain in the Leave A Comment is to use the Events tab and the Add Variable. The right click only shows the Global Variable, at least with build 104

Tuesday, October 02, 2012 at 8:46:38 PM
0
kittiewan 12.2k rep

Thanks, SocalSam. I updated the tutorial to reflect your comment.

Tuesday, October 02, 2012 at 9:48:30 PM
0
paperartist 2,359 rep

nice tutorial ^_^d

Sunday, March 03, 2013 at 2:29:11 PM
0
jegcelorio 3,723 rep

Great tutorial!!! Knowing how to randomize values is definitely a basic skill that every game programmer should know!

Monday, March 25, 2013 at 9:30:28 PM
0
Asatur 2,798 rep

Great 10x :D

Tuesday, March 26, 2013 at 7:13:17 PM
0
randy70 2,798 rep

Thanks for this tutorial. Very helpful.

Saturday, November 09, 2013 at 10:58:22 PM
0
flemmig 8,809 rep

Hi

Fine tutor BUT how can I do this with a SPRITE
that has 15 frames

R/
Flemming

Thursday, November 14, 2013 at 3:20:56 PM
0
lo7s 758 rep

Thx for your tutorial ! I was struggling to find a way to make pick unique frame.I did thx to you.

Wednesday, January 01, 2014 at 1:16:22 PM
1
Lordshiva1948 41.5k rep

Thank for this nice one

Friday, February 21, 2014 at 1:30:04 PM
0
CurioJoe 1,040 rep

Can you explain lesson eight, I got lost at that point, I can't get it to contain the value.

Saturday, April 12, 2014 at 4:12:19 AM
4
steve85 404 rep

There's a simpler, (much) faster AND guaranteed way to do what the tutorial attempts..
However, my approach assumes that you know all the unique values beforehand (ex: animation frames, enemies, colors, animals, numbers...)

-create an array to hold your unique values (numbers or strings)
[array size = number of unique values]
-fill each spot of the array with a unique value.
-randomize the array.
tada.. The array now contains random unique values!

If you'll only use each value once, just pop it off the back of the array until the array is emptied.
If you need to keep trace of used values, don't pop, instead keep an index (global number) pointing to the current value (array index/x).

For example, suppose you want to process unique frames of an animation randomly..

//creating and filling the array:
Array Set size to (number_of_frames, 1, 1)
Array For each X element{
Array Set value at Self.CurX to Self.CurX
//fill each index of the array with the index value itself!
//why? because array indexes are [0,1,..,array_size-1] also the animation frame numbers are [0,1,..,number_of_frames-1] and remember array_size = number_of_frames.
//this is a special scenario where our unique values happen to be the same as the array indexes! ;)
}

//randomizing the array:
Local number tmpIdx = 0
Local number tmpVal = 0
Array For each X element{
Set tmpIdx to floor(random(0, Array.Width))
Set tmpVal to Array.at(tmpIdx)
Array Set value at tmpIdx to Self.CurValue
Array Set value at Self.CurX to tmpVal
}

Sunday, April 13, 2014 at 3:46:56 PM

Leave a comment

Everyone is welcome to leave their thoughts! Register a new account or login.