Skip to content

Commit e42087b

Browse files
committed
Permutations with repetitive options
1 parent deac131 commit e42087b

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

src/sets/sets.js

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ export const getCartesianProductsUnlimitedSets = (...sets) => {
4444
// Permutations algorithm - ordered combinations of values, can be without or with repetition
4545
// All possible combination of items with or without repetition
4646
// One extra loop per extra element inside input array
47+
// Time complexity: Factorial O(n!) ( 4 * 3 * 2 * 1 => 24; 5 * 4 * 3 * 2 * 1 => 120)
4748
export const getAllPermutations = (options) => {
4849
const possibleOptions = [];
4950
if (options.length === 1) {
@@ -66,4 +67,24 @@ export const getAllPermutations = (options) => {
6667
return possibleOptions;
6768
};
6869

69-
console.log(getAllPermutations(["a", "b", "c"]));
70+
// Permutation algorithm with repetitive values
71+
export const getAllPermutationsWithRepetition = (
72+
options,
73+
combinationLength
74+
) => {
75+
const possibleOptions = [];
76+
if (combinationLength === 1) return options.map((option) => [option]);
77+
const partialOption = getAllPermutationsWithRepetition(
78+
options,
79+
combinationLength - 1
80+
);
81+
82+
for (const option of options) {
83+
for (const existingOption of partialOption) {
84+
possibleOptions.push([option].concat(existingOption));
85+
}
86+
}
87+
return possibleOptions;
88+
};
89+
90+
console.log(getAllPermutationsWithRepetition([1, 2, 3], 2).length);

src/sets/sets.test.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
getCartesianProductsForOf,
33
getCartesianProductsUnlimitedSets,
44
getAllPermutations,
5+
getAllPermutationsWithRepetition,
56
} from "./sets";
67

78
describe("Cartesian Product", () => {
@@ -71,3 +72,42 @@ describe("Permutations", () => {
7172
]);
7273
});
7374
});
75+
76+
describe("Permutations with repetitive items, predefined combination length", () => {
77+
test("Get All Permutations with repetitive items", () => {
78+
expect(getAllPermutationsWithRepetition([1, 2, 3], 3)).toStrictEqual([
79+
[1, 1, 1],
80+
[1, 1, 2],
81+
[1, 1, 3],
82+
[1, 2, 1],
83+
[1, 2, 2],
84+
[1, 2, 3],
85+
[1, 3, 1],
86+
[1, 3, 2],
87+
[1, 3, 3],
88+
[2, 1, 1],
89+
[2, 1, 2],
90+
[2, 1, 3],
91+
[2, 2, 1],
92+
[2, 2, 2],
93+
[2, 2, 3],
94+
[2, 3, 1],
95+
[2, 3, 2],
96+
[2, 3, 3],
97+
[3, 1, 1],
98+
[3, 1, 2],
99+
[3, 1, 3],
100+
[3, 2, 1],
101+
[3, 2, 2],
102+
[3, 2, 3],
103+
[3, 3, 1],
104+
[3, 3, 2],
105+
[3, 3, 3],
106+
]);
107+
});
108+
test("Get All Permutations with repetitive items", () => {
109+
expect(getAllPermutationsWithRepetition([1], 2)).toStrictEqual([
110+
[1, 1],
111+
]);
112+
});
113+
});

0 commit comments

Comments
 (0)