-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Get permutations of arrays and strings recursively
- Loading branch information
Showing
2 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
const permutations = (input) => { | ||
const isString = typeof input === 'string'; | ||
|
||
if (isString) { | ||
if (input.length < 2) { | ||
return [input]; | ||
} | ||
|
||
input = input.split(''); | ||
} else if (!Array.isArray(input) || input.length < 2) { | ||
return [input]; | ||
} | ||
|
||
const output = []; | ||
|
||
const perms = permutations(input.slice(1)); | ||
const current = input[0]; | ||
|
||
for (let i = 0; i < perms.length; i++) { | ||
const perm = perms[i]; | ||
|
||
for (let position = 0; position < input.length; position++) { | ||
const add = [...perm.slice(0, position), current, ...perm.slice(position, perm.length)]; | ||
|
||
output.push(add); | ||
} | ||
} | ||
|
||
if (isString) { | ||
for (let i = 0; i < output.length; i++) { | ||
output[i] = output[i].join(''); | ||
} | ||
} | ||
|
||
return output; | ||
}; | ||
|
||
export default permutations; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import permutations from './permutations'; | ||
|
||
describe('permutations', () => { | ||
const cases = [ | ||
['a', ['a']], | ||
[[1], [[1]]], | ||
[[0, 1], [[0, 1], [1, 0]]], | ||
['01', ['01', '10']], | ||
[[0, 1, 2], [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]], | ||
[null, [null]], | ||
[undefined, [undefined]], | ||
[{}, [{}]], | ||
[123, [123]], | ||
[false, [false]] | ||
]; | ||
|
||
for (let i = 0; i < cases.length; i++) { | ||
const [ input, output ] = cases[i]; | ||
it(`${JSON.stringify(input)} returns ${JSON.stringify(output)}`, () => { | ||
expect(permutations(input)).toEqual(expect.arrayContaining(output)); | ||
}); | ||
} | ||
}); |