|
| 1 | +import assert from 'assert'; |
| 2 | +import {_take} from '@iterable-iterator/slice'; |
| 3 | + |
| 4 | +import {list} from '@iterable-iterator/list'; |
| 5 | +import {pick} from '@iterable-iterator/map'; |
| 6 | +import {range} from '@iterable-iterator/range'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Yields all permutations of each possible choice of <code>r</code> elements |
| 10 | + * of the input iterable. |
| 11 | + * |
| 12 | + * @example |
| 13 | + * // AB AC AD BA BC BD CA CB CD DA DB DC |
| 14 | + * permutations('ABCD', 2) ; |
| 15 | + * |
| 16 | + * @example |
| 17 | + * // 012 021 102 120 201 210 |
| 18 | + * permutations(range(3), 3) ; |
| 19 | + * |
| 20 | + * @param {Iterable} iterable - The input iterable. |
| 21 | + * @param {number} r - The size of the permutations to generate. |
| 22 | + * @returns {IterableIterator} |
| 23 | + */ |
| 24 | +export default function* permutations(iterable, r) { |
| 25 | + assert(Number.isInteger(r) && r >= 0); |
| 26 | + const pool = list(iterable); |
| 27 | + |
| 28 | + const length = pool.length; |
| 29 | + |
| 30 | + if (r > length) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + const indices = list(range(0, length, 1)); |
| 35 | + const cycles = list(range(length, length - r, -1)); |
| 36 | + |
| 37 | + yield list(pick(pool, _take(indices, r))); |
| 38 | + |
| 39 | + if (r === 0 || length === 0) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + while (true) { |
| 44 | + let i = r; |
| 45 | + |
| 46 | + while (i--) { |
| 47 | + --cycles[i]; |
| 48 | + |
| 49 | + if (cycles[i] === 0) { |
| 50 | + // Could be costly |
| 51 | + indices.push(indices.splice(i, 1)[0]); |
| 52 | + |
| 53 | + cycles[i] = length - i; |
| 54 | + } else { |
| 55 | + const j = cycles[i]; |
| 56 | + |
| 57 | + [indices[i], indices[length - j]] = [indices[length - j], indices[i]]; |
| 58 | + |
| 59 | + yield list(pick(pool, _take(indices, r))); |
| 60 | + break; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + if (i === -1) { |
| 65 | + return; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments