Jump to content

Harmjan

Members
  • Posts

    1
  • Joined

  • Last visited

Harmjan's Achievements

Newbie

Newbie (1/7)

0

Reputation

  1. 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>
×
×
  • Create New...