What is the best way to randomly select numbers from 1 to 10 without repeating one?

Is there an efficient way to expand an integer into random, unique numbers?

I want to 10become 3 4 6 1 0 2 5 7 8 9.

I tried THIS ... but before pushing the values ​​into arrays and going crazy, I thought there might have been a better way.

EDIT:

HERE IS MY NEW FIDDLE AND FUNCTION:

function uniqueDigits(x){
    y = [];
    z = [];
    while(x > 0) {    
        y.push(x);
        x--;
    } 
    while(y.length > 0){
        var r = Math.floor(Math.random()*y.length);
        var u = y[r]
        y.splice(r, 1);
        z.push(u-1);
    }         
    return z;
}

uniqueDigits(4) //['2', '3', '0', '1']

EDIT:

AND HERE ANOTHER OPTION :

function uniqueNum(x){
  z = y = x;
  var r = Math.ceil(Math.random() * x);

  while ( x%r%2 == 0 ) {
    r = Math.ceil(Math.random() * x);
  }

  while( x>0 ){
    y = y - r     
    if(y<0){ 
      var n = y; 
      y = z + n 
    }   
    $('p').append(y);
    x--
   }    
} uniqueNum(4);//['2', '3', '0', '1']

OR THIS too

Alright, I'm done.

+3
source share
3 answers

Since you are looking for the whole number in a range, try

var x = 10,
    array = [];
for (var y = 0; y < x; y++) {
    array.push(y);
}
while (array.length) {
    var random = Math.floor(Math.random() * array.length);
    $('p').append(array.splice(random, 1));
}

Demo: Fiddle


Another way to use an array is

var x = 10,
    array = [];
//used for counting the loop for performance testing - remove it
var counter = 0;
for (var y = 0; y < x;) {
    var random = Math.floor(Math.random() * x);
    if ($.inArray(random, array) == -1) {
        $('p').append(random);
        array.push(random);
        y++;        
    }
    //for test
    counter++;
}
console.log(counter)

: Fiddle -

+3

, , ,

- - - ( ) .

from () javascript?.

, :

var x = 10;
var range = [];
for (var y = 0; y < x; y++) {
    range.push(y);
}
function shuffle(array) {
  var currentIndex = array.length
    , temporaryValue
    , randomIndex
    ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
}
shuffle(range);
+1

:

function getRandomNonRepeatedInt(limit)
{
    var array = [], result = "";
    for (var y = 0; y <= limit-1; array.push(y), y++);
    while (array.length) result = result + array.splice(Math.floor(Math.random() * array.length), 1)[0];
    return result;
}

...: -)

Fiddle

0

All Articles