Skip to content

Commit 8cb5644

Browse files
authored
Merge pull request TheAlgorithms#458 from piemme/adding-string-permutation-algorithm
Add Algorithm String Permutation
2 parents 651f749 + 7aa9410 commit 8cb5644

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

String/PermutateString.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict'
2+
3+
const permutate = (aString) => {
4+
if (typeof aString !== 'string' || !aString) {
5+
throw new Error('The arg must be a valid, non empty string')
6+
}
7+
const characters = aString.split('')
8+
let permutations = [[characters.shift()]]
9+
while (characters.length) {
10+
const currentCharacter = characters.shift()
11+
permutations = calculateCurrentCharacterPermutation(permutations, currentCharacter)
12+
}
13+
return permutations
14+
.map(character => character.join(''))
15+
.filter((item, index, self) => (self.indexOf(item) === index))
16+
.sort()
17+
}
18+
19+
const calculateCurrentCharacterPermutation = (allPermutations, currentCharacter) => {
20+
const currentPermutations = []
21+
allPermutations.map(permutation => {
22+
let index = 0
23+
while (index <= permutation.length) {
24+
const tmp = [...permutation]
25+
tmp.splice(index, 0, currentCharacter)
26+
currentPermutations.push(tmp)
27+
index++
28+
}
29+
})
30+
return currentPermutations
31+
}
32+
33+
export { permutate }

String/PermutateString.test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { permutate } from './PermutateString'
2+
3+
describe('Permutate a string', () => {
4+
it('expects to throw an Error with an empty string', () => {
5+
expect(() => { permutate() }).toThrow('The arg must be a valid, non empty string')
6+
})
7+
it('expects to permute "no" into [no, on]', () => {
8+
expect(['no', 'on']).toEqual(permutate('no'))
9+
})
10+
it('expects to permute "yes" into [esy, eys, sey, sye, yes, yse]', () => {
11+
expect(['esy', 'eys', 'sey', 'sye', 'yes', 'yse']).toEqual(permutate('yes'))
12+
})
13+
it('expects to permute "good" into [dgoo dogo doog gdoo godo good odgo odog ogdo ogod oodg oogd ]', () => {
14+
expect(['dgoo', 'dogo', 'doog', 'gdoo', 'godo', 'good', 'odgo', 'odog', 'ogdo', 'ogod', 'oodg', 'oogd'])
15+
.toEqual(permutate('good'))
16+
})
17+
})

0 commit comments

Comments
 (0)