Skip to content
44 changes: 44 additions & 0 deletions src/data/array_functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,50 @@ define(function (require) {
return list;
};

/**
* Randomizes the order of the elements of an array.
* Implements Fisher-Yates Shuffle Algorithm
* http://Bost.Ocks.org/mike/shuffle/
* http://en.Wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*
* @method shuffle
* @param {Array} array Array to shuffle
* @param {Boolean} [bool] modify passed array
* @return {Array} shuffled Array
* @example
* <div><code>
* function setup() {
* const regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
* print(regularArr);
* shuffle(regularArr, true); // Forced modifications to passed array!
* print(regularArr), print('');
*
* // By default shuffle() returns a shuffled cloned array:
* const clonedArr = shuffle(regularArr);
* print(regularArr), print(clonedArr), print('');
*
* const typedArr = new Uint8ClampedArray([10, 20, 30, 40, 50]);
* print(typedArr);
* shuffle(typedArr); // TypedArrays are never cloned!
* print(typedArr), print('');
* }
* </code></div>
*/
p5.prototype.shuffle = function(arr, bool) {
arr = bool || ArrayBuffer.isView(arr)? arr : arr.slice();

var rnd, tmp, idx = arr.length;
while (idx > 1) {
rnd = Math.random()*idx | 0;

tmp = arr[--idx];
arr[idx] = arr[rnd];
arr[rnd] = tmp;
}

return arr;
};

/**
* Sorts an array of numbers from smallest to largest, or puts an array of
* words in alphabetical order. The original array is not modified; a
Expand Down