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!
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
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.