0

Possible Duplicate:
How to randomize a javascript array?

Hello guys I know how to generate a random value with Math.random() in Javascript, but can you tell me how to mix numbers randomly?

For example I have numbers 1,2,3,4,5,6,7,8,9,10 how to mix it randmoly like this: 2,8,9,1... so each number should be used only once

Community
  • 1
  • 1
Irakli
  • 1,151
  • 5
  • 30
  • 55

2 Answers2

1

You could do this by putting them all in an array and sort that array in a random fashion.

var nrs = [1,2,3,4,5,6,7,8,9,10];
nrs.sort(function(a,b){
    return Math.floor(Math.random()*3 - 1);
});
Pirokiko
  • 309
  • 1
  • 6
  • Yest it may be a solution but what do you think about `return 0.5 - Math.random()` instead of `return Math.floor(Math.random()*3 - 1); ` – Irakli Aug 19 '12 at 18:29
  • 1
    Poor solutions, both. See http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html. See the linked dupe for a better solution. – Michael Petrotta Aug 19 '12 at 18:31
  • @Irakli That would actually be slightly less random, not that this is more than pseudo-random anyway, because it is highly unlikely that you return a 0 which also influences the resulting order of numbers – Pirokiko Aug 21 '12 at 18:15
  • @MichaelPetrotta I didn't really think from his question that he wanted anything close to true randomization, though what you say is true. Also, that was a pretty good read. – Pirokiko Aug 21 '12 at 18:18
0
var nums = [1,2,3,4,5,6,7,8,9,10], numsMixed = [];
while(nums.length){
  numsMixed = numsMixed.concat(nums.splice((Math.random() * nums.length), 1));
}
console.log(numsMixed);
Diode
  • 24,570
  • 8
  • 40
  • 51