basant307/AI_Governance_Project
045
1/**2 * Obliterator Permutations Function3 * ==================================4 *5 * Iterator returning permutations of the given array.6 */7var Iterator = require('./iterator.js');8 9/**10 * Helper mapping indices to items.11 */12function indicesToItems(target, items, indices, r) {13 for (var i = 0; i < r; i++) target[i] = items[indices[i]];14}15 16/**17 * Permutations.18 *19 * @param {array} array - Target array.20 * @param {number} r - Size of the subsequences.21 * @return {Iterator}22 */23module.exports = function permutations(array, r) {24 if (!Array.isArray(array))25 throw new Error(26 'obliterator/permutations: first argument should be an array.'27 );28 29 var n = array.length;30 31 if (arguments.length < 2) r = n;32 33 if (typeof r !== 'number')34 throw new Error(35 'obliterator/permutations: second argument should be omitted or a number.'36 );37 38 if (r > n)39 throw new Error(40 'obliterator/permutations: the size of the subsequences should not exceed the length of the array.'41 );42 43 var indices = new Uint32Array(n),44 subsequence = new Array(r),45 cycles = new Uint32Array(r),46 first = true,47 i;48 49 for (i = 0; i < n; i++) {50 indices[i] = i;51 52 if (i < r) cycles[i] = n - i;53 }54 55 i = r;56 57 return new Iterator(function next() {58 if (first) {59 first = false;60 indicesToItems(subsequence, array, indices, r);61 return {value: subsequence, done: false};62 }63 64 var tmp, j;65 66 i--;67 68 if (i < 0) return {done: true};69 70 cycles[i]--;71 72 if (cycles[i] === 0) {73 tmp = indices[i];74 75 for (j = i; j < n - 1; j++) indices[j] = indices[j + 1];76 77 indices[n - 1] = tmp;78 79 cycles[i] = n - i;80 return next();81 } else {82 j = cycles[i];83 tmp = indices[i];84 85 indices[i] = indices[n - j];86 indices[n - j] = tmp;87 88 i = r;89 90 indicesToItems(subsequence, array, indices, r);91 return {value: subsequence, done: false};92 }93 });94};95 