# Unique Random Number Generation Troubles

Greetings,

I’m attempting to build a list of 5 random and unique numbers out of a range of 1 to X.

My current attempt is messy and complex, where I have a loop selecting a random number, then a second loop checking that number against the previously selected numbers and then stuffing it in into an array if it’s unique.

I get so many errors that I’m wondering if I have some sort of strict mode enabled. Even a simple for loop like this generates Unexpected ; errors:

``````var _total_hand:Int = 5;
for ( var i = 0; i < _total_hand; i++ ) {}
``````

Then, I saw a more elegant approach written in another language that goes like this:

``````Dim nums = Enumerable.Range(1, 10).OrderBy(Function(r) RNG.Next).Take(3).ToArray();
``````

Here, a range of unique numbers are generated from 1 to 10, then randomized, then the first 3 are dropped into an array. This guarantees each number is unique without having complicated loops.

I’m struggling to translate this into the correct syntax that I can use in openfl. I would appreciate any assistance you guys could give me. Thanks!

Hi, this isn’t the most elegant but it might be helpful. https://try.haxe.org/#91d83

The haxe way to do a for loop is:

``````for (i in 0...10)
{
...
}
``````

EDIT:
This example is geared to a deck of cards.
https://try.haxe.org/#57a19

1 Like

Here’s a library that might also help

3 Likes

Hello there,

check this out https://en.wikipedia.org/wiki/Fisher–Yates_shuffle

Basically you only need a second loop just for do a randow switch beetween elements of the array, at the end, you will always got a random array with unique elements and it wont messy around with conditionals checking if theres unique elements.

example

//WARNING this code could be improve a lot, but right now im a little rusty with haxe.

var arr:Array=new Array();

//Loop 1 Creational loop, lets say the range is from 1 to 50

for ( i in 0…50 )
arr.push(i+1);

//Loop 2 Shuffle Loop

var num_shuffle=arr.length; // this value can even be arr.length * x [ 1.5 , 2, 3 ,…n How many iterations you desire ]

for ( i in 0…num_shuffle ) {
var rnd_pos=Math.round(Math.random()*(arr.length-1));
var j=arr[i];
arr[i]=arr[rnd_pos];
arr[rnd_pos]=j;
}

trace(arr);

this is how i can shuffle the pieces of my puzzle game fidget spinner puzzle

https://www.openfl.org/showcase/title/fidget-spinner-puzzle/

Please let me know if this helps you or is the answer to your question. Have a good day

1 Like

If you want a version of hxrandom that uses the Fisher-Yates shuffle, check out my fork. (The original implementation contains this error.)

1 Like

Oh man, thanks so much all of you. There are some great solutions in here that work great for what I was looking for. Thanks for taking some time to help me out. Sorry this reply is so late in coming, Holidays then a week of being sick has kept me from the project.

Thanks again!