how to get distinct permutations of a set in typescript

index.ts
function getPermutations(set: Set<any>): any[][] {
    const result = [];
    const inputArr = Array.from(set);

    function permute(arr: any[], m: any[] = []): void {
        if (arr.length === 0) {
            result.push(m);
        } else {
            for (let i = 0; i < arr.length; i++) {
                const curr = arr.slice();
                const next = curr.splice(i, 1);
                permute(curr.slice(), m.concat(next));
            }
        }
    }

    permute(inputArr);

    const distinctResult = [];
    const strResult = [];

    // stringify permutations to identify and remove duplicates
    for (let i = 0; i < result.length; i++) {
        const str = JSON.stringify(result[i]);
        if (!strResult.includes(str)) {
            strResult.push(str);
            distinctResult.push(result[i]);
        }
    }

    return distinctResult;
}
875 chars
33 lines

The getPermutations function takes a set as an argument and utilizes a recursive backtracking algorithm to calculate all possible permutations. To ensure that the resulting permutations are distinct, each permutation is also stringified and checked for duplicates before adding it to the final list of results.

gistlibby LogSnag