Javascript : Making An Random Array
Possible Duplicate: Generate unique number within range (0 - X), keeping a history to prevent duplicates Writing a function that make random array,as I wrote below: RandomArray(
Solution 1:
This is one way to do it:
var RandomArray = functionRandomArray(elements) {
var min = 0, //minrandom number
max = 15, //maxrandom number
i, //incrementer
arr = []; //output
//generate an array of length (elements) containing random number from min to maxfor (i = 0; i < elements; i += 1) {
arr.push(Math.floor(Math.random() * (max + 1)) + min);
}
//return the array
return arr;
};
Here's a fiddle: http://jsfiddle.net/mKFk9/
Solution 2:
This might be what you need:
/**
* range Get an array of numbers within a range
* @param min {number} Lowest number in array
* @param max {number} Highest number in array
* @param rand {bool} Shuffle array
* @return {array}
*/functionrange( min, max, rand ) {
var arr = ( newArray( ++max - min ) )
.join('.').split('.')
.map(function( v,i ){ return min + i })
return rand
? arr.map(function( v ) { return [ Math.random(), v ] })
.sort().map(function( v ) { return v[ 1 ] })
: arr
}
Solution 3:
functionrandomArray(n) {
vararray = [];
for (i = 0; i < n; i++) {
array[i] = i;
}
var newArray = [];
for (i = 0; i < n; i++) {
var num = Math.round(Math.random() * (n - i - 1));
newArray[i] = array[num];
array.splice(num, 1);
}
alert(newArray);
}
randomArray(100);
Post a Comment for "Javascript : Making An Random Array"