@beenotung/tslib
Version:
utils library in Typescript
35 lines (34 loc) • 1.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.combinations = void 0;
exports.any_combinations = any_combinations;
exports.n_combinations = n_combinations;
/**
* @description combination: order doesn't matter
* @description known bug: will have integer overflow when the list is too long
*/
function any_combinations(xs) {
const xss = [];
const listLen = xs.length;
const combinationCount = 1 << listLen;
for (let i = 1; i < combinationCount; i++) {
const ys = [];
for (let j = 0; j < listLen; j++) {
if (i & (1 << j)) {
ys.push(xs[j]);
}
}
xss.push(ys);
}
return xss;
}
/** @description combination: order doesn't matter */
function n_combinations(n, xs) {
if (n == 0)
return [];
if (n == 1)
return xs.map(x => [x]);
return xs.flatMap((x, i) => n_combinations(n - 1, xs.slice(i + 1)).map(xs => [x, ...xs]));
}
/** @deprecated renamed to `any_combinations` */
exports.combinations = any_combinations;