1

My function that shuffles an array and then returns it isn't working properly, and I can't understand why.

numbers.sort(function() { return Math.round(Math.random()); } );
return numbers;

This works, however the first item in the array is always the same.

does anyone know why?

a-second-mix
  • 372
  • 3
  • 10
  • possible duplicate of [Javascript Random problem ?](http://stackoverflow.com/questions/4331155/javascript-random-problem) – deceze May 31 '11 at 08:53
  • 1
    It is not a good idea to use a `random()` as a `sort()` function. Most `sort()` routines require their functions to give a total ordering of inputs so that they perform at all reasonable: http://stackoverflow.com/questions/4129995/why-does-using-random-in-sort-causing-unable-to-sort-icomparer-compare-error – sarnold May 31 '11 at 08:55
  • @deceze I don't think so, but your link contains the answer for his question. – Reporter May 31 '11 at 08:56
  • Thanks for the responses guys. @deceze that link you posted was exactly what I needed. I used a for loop, and all is well :) – a-second-mix May 31 '11 at 09:13
  • possible duplicate of [Is it correct to use JavaScript Array.sort() method for shuffling?](http://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling) – Ja͢ck Jan 30 '13 at 13:27

2 Answers2

3

That's no way to sort. You tell the sorter that one value is greater than the other, while on a next request it can be smaller. Who knows wat might happen. The sorter may take long, perform badly, or you might rip the very fabric of which the universe is made of.

If you want to sort a deck of cards, I think it is better to loop though all cards and swap each of them with a random other card. That way, you're sure the whole deck is shuffeled in only one iteration.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
-1

use Math.floor() instead Math.round()

Oleg
  • 798
  • 3
  • 7
  • Math.floor(Math.random()) will always return 0, while round will return 0 or 1, but never -1. Neither is as good a shuffle as array.sort(function(){return .5-Math.random()}) – kennebec May 31 '11 at 12:50