-
Different Random Numbers
I know how to randomize numbers. How can you make it so random numbers can not equal each other? Also, how do you make it so none of the numbers are a specific number? If you don't understand, this is what I mean:
Code:
NumberA = random(10);
NumberB = random(10);
NumberC = random(10);
NumberD = random(10);
NumberE = random(10);
NumberF = random(10);
NumberG = random(10);
NumberH = random(10);
NumberI = random(10);
How can you make it so each number is different and none of them are 0?
-
offhand, i can think of at least one method to figure this out.
you could set up an array of all the possible numbers you want your variables to be set as and loop through it, assigning a variable a random index from the array, and then splice that number out of the array. and to make sure that none of the numbers are 0, just add the minimum a number can be after the random statement
(NumberA = random(10)+numMin)
-
Use Array and shuffle it:-
Code:
//method for shuffling an array
Array.prototype.shuffle=function(){
for(i=0;i<this.length;i++){
var tmp=this[i];
var randomNum=random(this.length);
this[i]=this[randomNum];
this[randomNum]=tmp;
}
}
numberStorageArray = [1,2,3,4,5,6,7,8,9,10];
numberStorageArray.shuffle();
trace(numberStorageArray);
-
Using that code, how do you make it so the numbers are assigned randomly to the variables NumberA, NumberB, etc.? The numbers only seem to come out in the output.
-
Code:
// list of letters for identification
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I"];
// method for assigning numbers
Array.prototype.assign=function(){
for (i=0;i<letters.length;i++) {
_root["Number"+letters[i]]=this[i];
trace("Number"+letters[i]+": " + _root["Number"+letters[i]]);
}
}
//method for shuffling an array
Array.prototype.shuffle=function(){
for(i=0;i<this.length;i++){
var tmp=this[i];
var randomNum=random(this.length);
this[i]=this[randomNum];
this[randomNum]=tmp;
}
}
numberStorageArray = [1,2,3,4,5,6,7,8,9];
numberStorageArray.shuffle();
numberStorageArray.assign();
trace(numberStorageArray);
/* OUTPUT
NumberA: 4
NumberB: 8
NumberC: 2
NumberD: 9
NumberE: 7
NumberF: 5
NumberG: 3
NumberH: 1
NumberI: 6
4,8,2,9,7,5,3,1,6
*/
-