Advertisement
LimePaste888

Randomize an array in JavaScript

Aug 22nd, 2022 (edited)
907
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // For the people trying to find a simple script that is actually readable to randomize an array/list, here you go
  2. function randomize(length) {
  3.     a = []
  4.     b = []
  5.     length++
  6.     // Make a an ascending list. (This isn't a typo you moron.)
  7.     for (i=0;i<length;i++) {
  8.         a.push(i)
  9.     }
  10.     // Main loop
  11.     while (length > 1) {
  12.         rng = Math.floor(Math.random()*a.length)
  13.         b.push(a[rng])
  14.         a.splice(rng,1)
  15.         length--
  16.     }
  17.     return b
  18. }
  19. // Example: randomize(2) can return [0, 1] or [1, 0]
  20. // randomize(6) can return [2, 5, 3, 1, 0, 4]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement