Julio M. February 2016

I need to disorder an array

Hello I need disorder an array. I tryed something like this:

var letras = ['a', 'e', 'i', 'o', 'u'];

function disorder(p){

  for(i=0;i<100;i++){
    pos = Math.random()*p.length;
    temp=p[pos];
    p.splice(pos,1);
    p.push(temp);
  }
}

But it doesnt work, and I am not sure that was memory efficient because of the deletes.

Answers


Nina Scholz February 2016

You need an integer as index.

pos = Math.random() * p.length | 0;

The bitwise or cast the value to integer.

function disorder(p) {
    var i, pos, temp;
    for (i = 0; i < 100; i++) {
        pos = Math.random() * p.length | 0;
        temp = p[pos];
        p.splice(pos, 1);
        p.push(temp);
    }
}

var letras = ['a', 'e', 'i', 'o', 'u'], p = []

disorder(letras);
document.write('<pre>' + JSON.stringify(letras, 0, 4) + '</pre>');


Matthew Herbst February 2016

How about just doing a random sort?

var letras = ['a', 'e', 'i', 'o', 'u'];

function disorder(arr, entropy){
  var disorderedArr = arr.sort(function(a, b) {
    return Math.floor(Math.random() * entropy); 
  });

  return disorderedArr;
}

var disorderedLetras = disorder(letras, 10);
console.log(disorderedLetras);
document.write('<pre>' + JSON.stringify(disorderedLetras, 0, 4) + '</pre>');

While probably not statistically vigorous, this will do what you want and gives you some control over how random things actually will be.

Post Status

Asked in February 2016
Viewed 1,852 times
Voted 7
Answered 2 times

Search




Leave an answer