UNPKG

chopsuey

Version:

Combinatorics: subsets, permutations, etc.

52 lines (51 loc) 1.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChopSuey = void 0; class ChopSuey { static *generateSubsets(elements, offset = 0) { while (offset < elements.length) { const first = elements[offset++]; for (const subset of this.generateSubsets(elements, offset)) { subset.push(first); yield subset; } } yield []; } static *generatePermutations(elements) { yield elements.slice(); const stack = Array(elements.length).fill(0); let i = 1; while (i < elements.length) { if (stack[i] < i) { const j = i % 2 && stack[i]; [elements[i], elements[j]] = [elements[j], elements[i]]; stack[i]++; i = 1; yield elements.slice(); } else { stack[i] = 0; i++; } } } static getSubsets(elements) { return [...this.generateSubsets(elements)]; } static getPermutations(elements) { return [...this.generatePermutations(elements)]; } static getShuffled(elements) { const shuffle = (copyElements) => { for (let i = copyElements.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [copyElements[i], copyElements[j]] = [copyElements[j], copyElements[i]]; } }; const copy = elements.slice(); shuffle(copy); return copy; } } exports.ChopSuey = ChopSuey;