shuffle/fisheryates.js

  1. (function (exports) {
  2. 'use strict';
  3. /**
  4. * The shuffling algorithm of
  5. * Fisher-Yates.<br><br>
  6. * Time complexity: O(N).
  7. *
  8. * @example
  9. * var shuffle = require('path-to-algorithms/src/' +
  10. * 'shuffle/fisheryates').shuffle;
  11. * console.log(shuffle([1, 2, 3, 4, 5])); // shuffled array
  12. *
  13. * @public
  14. * @module shuffle/fisheryates
  15. * @param {Array} array Array which should be shuffled.
  16. * @return {Array} Shuffled array.
  17. */
  18. function shuffle(array) {
  19. var size = array.length;
  20. var rand;
  21. for (var i = 0; i < size; i += 1) {
  22. rand = Math.floor(i + Math.random() * (size - i));
  23. [array[rand], array[i]] = [array[i], array[rand]];
  24. }
  25. return array;
  26. }
  27. exports.shuffle = shuffle;
  28. })(typeof window === 'undefined' ? module.exports : window);