@@ -31,10 +31,39 @@ export const getCartesianProductsForOf = (colors, sizes) => {
31
31
} ;
32
32
33
33
// 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)
34
36
export const getCartesianProductsUnlimitedSets = ( ...sets ) => {
35
37
let options = sets [ 0 ] ;
36
38
for ( let i = 1 ; i < sets . length ; i ++ ) {
37
39
options = getCartesianProductsForOf ( options , sets [ i ] ) ;
38
40
}
39
41
return options ;
40
42
} ;
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" ] ) ) ;
0 commit comments