Skip to content

Commit

Permalink
Get permutations of arrays and strings recursively
Browse files Browse the repository at this point in the history
  • Loading branch information
grxy committed Mar 10, 2017
1 parent cad15ad commit 20dbbef
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/permutations/permutations.js
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;
23 changes: 23 additions & 0 deletions src/permutations/permutations.test.js
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));
});
}
});

0 comments on commit 20dbbef

Please sign in to comment.