File tree Expand file tree Collapse file tree 1 file changed +18
-8
lines changed
Expand file tree Collapse file tree 1 file changed +18
-8
lines changed Original file line number Diff line number Diff line change 11const permutations = function (
22 original ,
3- currentPermutations = original . map ( ( num ) => [ num ] ) ,
3+ partialPermutations = original . map ( ( num ) => [ num ] ) ,
44) {
5- if ( original . length < 2 ) return [ original ] ;
5+ if ( original . length <= 1 ) return [ original ] ;
66
7- const newPerms = [ ] ;
8- currentPermutations . forEach ( ( el ) => {
9- const missing = original . filter ( ( item ) => ! el . includes ( item ) ) ;
10- missing . forEach ( ( itemMissing ) => newPerms . push ( [ ...el , itemMissing ] ) ) ;
7+ const newPartialPermutations = [ ] ;
8+ partialPermutations . forEach ( ( partialPermutation ) => {
9+ const missingNums = original . filter (
10+ ( num ) => ! partialPermutation . includes ( num ) ,
11+ ) ;
12+ missingNums . forEach ( ( missingNum ) =>
13+ newPartialPermutations . push ( [ ...partialPermutation , missingNum ] ) ,
14+ ) ;
1115 } ) ;
1216
13- if ( newPerms . every ( ( el ) => el . length === original . length ) ) return newPerms ;
14- return permutations ( original , newPerms ) ;
17+ // We can pick any valid index because all of the elements will be the same length
18+ const ANY_INDEX = 0 ;
19+
20+ if ( newPartialPermutations [ ANY_INDEX ] . length === original . length ) {
21+ return newPartialPermutations ;
22+ }
23+
24+ return permutations ( original , newPartialPermutations ) ;
1525} ;
1626
1727// Do not edit below this line
You can’t perform that action at this time.
0 commit comments