basant307/AI_Governance_Project
045
1/**2 * Obliterator Combinations Function3 * ==================================4 *5 * Iterator returning combinations 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 * Combinations.18 *19 * @param {array} array - Target array.20 * @param {number} r - Size of the subsequences.21 * @return {Iterator}22 */23module.exports = function combinations(array, r) {24 if (!Array.isArray(array))25 throw new Error(26 'obliterator/combinations: first argument should be an array.'27 );28 29 var n = array.length;30 31 if (typeof r !== 'number')32 throw new Error(33 'obliterator/combinations: second argument should be omitted or a number.'34 );35 36 if (r > n)37 throw new Error(38 'obliterator/combinations: the size of the subsequences should not exceed the length of the array.'39 );40 41 if (r === n) return Iterator.of(array.slice());42 43 var indices = new Array(r),44 subsequence = new Array(r),45 first = true,46 i;47 48 for (i = 0; i < r; i++) indices[i] = i;49 50 return new Iterator(function next() {51 if (first) {52 first = false;53 54 indicesToItems(subsequence, array, indices, r);55 return {value: subsequence, done: false};56 }57 58 if (indices[r - 1]++ < n - 1) {59 indicesToItems(subsequence, array, indices, r);60 return {value: subsequence, done: false};61 }62 63 i = r - 2;64 65 while (i >= 0 && indices[i] >= n - (r - i)) --i;66 67 if (i < 0) return {done: true};68 69 indices[i]++;70 71 while (++i < r) indices[i] = indices[i - 1] + 1;72 73 indicesToItems(subsequence, array, indices, r);74 return {value: subsequence, done: false};75 });76};77 