Products
Technologies

Developer resources

Is there a way to assign placement of variables randomly?

Avg. Rating 5.0

Problem

I'm trying to get a random number between 1-3 to return non-repeating 3 times. There are 3 spaces and 3 variables that are to be placed and i need the order to be selected at random each time they are called. I'm thinking a non-repeating random number generator between the range of 1-3 would be best, however i do not know how to write a random number generator with a range included within itself.

Solution

This code takes a start and end value (both int) and generates an array. From there it shuffles the array into a random order and returns the shuffled array. This returned array can then be used in a simple for..loop for whatever you need without worrying about repeated values. Just make a call to the function each time you need a new series. This example could be modified to take an array of values instead of a start and end value.

Detailed explanation

Here is the code with a sample call that will generate an array with the values of 1,2,3 in a random order.

Any numbers can be passed in as values to generate a range, even negative numbers.

 

var a:Array = randomRange(1,3);
// var a:Array = randomRange(-5,5); 
// returns an array of 11 numbers from -5 to 5
trace(a);
//output after 5 calls
// 1,3,2
// 2,1,3
// 2,3,1
// 1,2,3
// 3,1,2

function randomRange(p_min:int, p_max:int):Array {

var p_arr:Array = [];
var i:int;

// Create the array of numbers from start to finish (inclusive)
for (i=p_min; i<=p_max; i++) {
  p_arr.push(i);
}

var shuffled:Array = [];
var cnt:Number = p_arr.length-1;

for (i=cnt; i>=0; i--) {
  var ranNum:Number = Math.floor(Math.random()*p_arr.length);
  // add the item from tmpList to shuffled
  shuffled.push(p_arr[ranNum]);

// remove the item from p_arr so it can't be used again
p_arr.splice(ranNum, 1);
} // return the shuffled return(shuffled); }

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes