Jump to content

JS: Array Sort: Sorting an Array in Random Order not correct


Recommended Posts

https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort_random

This code doesn't create a randomly ordered list:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});

When I run it multiple times and check on which index the 40 ended up, I get the following distribution:

29 %,16%, 10%, 11%, 14%, 19%.

I think it's dangerous to teach people a trick that doesn't work.

Full code:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>Click the button (again and again) to sort the array in random order.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<p id="demo2"></p>

<script>
let points;
let index;
document.getElementById("demo").innerHTML = points;  

function myFunction() {
for (let i = 0; i < 100000; i++){
	index = [0, 0, 0, 0, 0, 0];
    points = [40, 100, 1, 5, 25, 10];
      points.sort(function(a, b){return 0.5 - Math.random()});
    index[points.indexOf(40)]++;
    }
      document.getElementById("demo").innerHTML = points;
      document.getElementById("demo2").innerHTML = index;
}
</script>

</body>
</html>
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...