Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. /*
  2. The shuffle must be "uniform," meaning each item in the original array must have the same probability of ending up in each spot in the final array.
  3. Assume that you have a function getRandom(floor, ceiling) for getting a random integer that is >= floor and <= ceiling.
  4. */
  5. function getRandom(floor, ceiling) {
  6. return Math.floor(Math.random() * (ceiling - floor + 1)) + floor;
  7. }
  8.  
  9. function shuffle(array) {
  10.  
  11. // Shuffle the input in place
  12. for(let i = array.length -1; i>0; i--){
  13. let randomIndex = getRandom(0, i);
  14. let temp = array[randomIndex];
  15. array[randomIndex] = array[i];
  16. array[i] = temp;
  17. }
  18.  
  19. }
  20.  
  21.  
  22. const sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  23. console.log('Initial array: ', sample);
  24. shuffle(sample);
  25. console.log('Shuffled array: ', sample);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement