[removed] Making an random array [duplicate]

2019-09-15 17:27发布

问题:

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(10)

=> [0,2,3,9,6,5,4,7,8,1]

:(

I'm not learning progarming when school days so i wrote a ugly one.Here is my program.

var min = 0,
    max = 15,  //Here generate an random array from 0-14
    i,
    j,
    arr = [],
    temp = [];

for (i = min;i<max; i++){
    arr.push(i);
}

for(j=min;j<1000;j++){
   temp.push(arr[Math.floor(Math.random() * arr.length)]);  
}
function unique(array){
      var b = [];
      for(var i=0; i<array.length; i++){
         if(b.indexOf(array[i]) == -1) b.push(array[i]);
      }
      return b;
}
alert(unique(temp));

I wrote this program by searching the internet,it's not perfect i think, there is no arithmetic in it...

回答1:

This is one way to do it:

var RandomArray = function RandomArray(elements) {
    var min = 0,        //min random number
        max = 15,       //max random number
        i,              //incrementer
        arr = [];       //output
    //generate an array of length (elements) containing random number from min to max
    for (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/



回答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}
*/
function range( min, max, rand ) {
  var arr = ( new Array( ++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
}

Demo: http://jsfiddle.net/elclanrs/QBVbr/



回答3:

function randomArray(n) {

  var array = [];
  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);