0

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.

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128

2 Answers2

0

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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.

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128