Skip to content

Commit deac131

Browse files
committed
Get all possible permutations recursive
1 parent 8262b1a commit deac131

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/sets/sets.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,39 @@ export const getCartesianProductsForOf = (colors, sizes) => {
3131
};
3232

3333
// Unlimited amount of sets:
34+
// Time complexity: Assuming that all arrays have the same length O(n^x)
35+
// Space complexity: Assuming that all arrays have the same length O(n^x)
3436
export const getCartesianProductsUnlimitedSets = (...sets) => {
3537
let options = sets[0];
3638
for (let i = 1; i < sets.length; i++) {
3739
options = getCartesianProductsForOf(options, sets[i]);
3840
}
3941
return options;
4042
};
43+
44+
// Permutations algorithm - ordered combinations of values, can be without or with repetition
45+
// All possible combination of items with or without repetition
46+
// One extra loop per extra element inside input array
47+
export const getAllPermutations = (options) => {
48+
const possibleOptions = [];
49+
if (options.length === 1) {
50+
return [options];
51+
}
52+
const partialOptions = getAllPermutations(options.slice(1));
53+
54+
const firstOption = options[0];
55+
56+
for (let i = 0; i < partialOptions.length; i++) {
57+
const partialOption = partialOptions[i];
58+
for (let x = 0; x <= partialOptions.length; x++) {
59+
const optionInFront = partialOption.slice(0, x);
60+
const optionAfter = partialOption.slice(x);
61+
possibleOptions.push(
62+
optionInFront.concat([firstOption], optionAfter)
63+
);
64+
}
65+
}
66+
return possibleOptions;
67+
};
68+
69+
console.log(getAllPermutations(["a", "b", "c"]));

src/sets/sets.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
getCartesianProductsForOf,
33
getCartesianProductsUnlimitedSets,
4+
getAllPermutations,
45
} from "./sets";
56

67
describe("Cartesian Product", () => {
@@ -57,3 +58,16 @@ describe("Cartesian Product | Any amount of sets", () => {
5758
]);
5859
});
5960
});
61+
62+
describe("Permutations", () => {
63+
test("Get All Permutations", () => {
64+
expect(getAllPermutations(["a", "b", "c"])).toStrictEqual([
65+
["a", "b", "c"],
66+
["b", "a", "c"],
67+
["b", "c", "a"],
68+
["a", "c", "b"],
69+
["c", "a", "b"],
70+
["c", "b", "a"],
71+
]);
72+
});
73+
});

0 commit comments

Comments
 (0)