Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Math.random() >= 0.5 and Math.random() - 0.5

Tags:

javascript

I want to generate an array of length n, and the elements of the array are the random integer between 2 and 32. I use the function follow but I find that 17 will always be the first element of the returned array. What's more, when I change to sort function to sort(() => Math.random() - 0.5), it works well.

So I am confused that what's the difference betweenMath.random() >= 0.5 and Math.random() - 0.5? And how the difference affects the sort() function?

const fn = (n) => {
  let arr = [];
  for (let i = 2; i < 33; i++) {
    arr.push(i);
  }
  return arr.sort(() => Math.random() >= 0.5).slice(0, n)
}
like image 735
user3077147 Avatar asked Oct 14 '25 02:10

user3077147


1 Answers

You're not using sort for it's intended purpose, and the results are therefore unpredictable, weird and can vary between browser implementations. If you wish to shuffle an array, here is a far better function.

The function passed into Array.sort() should accept two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.

In your first try, you use sort(() => Math.random() >= 0.5), which returns a boolean; this is going to be cast to a 0 or a 1. This then means that your function is telling the sorter that whatever first argument you pass in is always going to be equal to or greater than whatever second argument you pass in. It just happens that 17 is passed in as the second argument every time your function is called; you tell the browser that it is therefore less than or equal to every other element in the array, and thus it will get put at the beginning of the array.

Your second attempt, with sort(() => Math.random() - 0.5), returns with equal probability that the first number is greater than the second, or vice versa, which makes the shuffle work much better. However, because of the unreliability of the whole thing there's zero assurance that the shuffle will work in all browsers or be particularly random. Please use the "real" shuffle algorithm linked above.

Source: http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort

like image 111
Richard Ye Avatar answered Oct 16 '25 15:10

Richard Ye