Jump to content

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


Harmjan
 Share

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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...