I'm trying to write a string permutation function, and I want to include all combinations of the letters ranging from 1 to n in size. I got this to work, but it includes duplicates:
output:
abc
ab
a
ba
b
a
acb
ac
a
ca
c
a
a
bac
ba
b
ab
a
b
bca
bc
b
cb
c
b
b
cab
ca
c
ac
a
c
cba
cb
c
bc
b
c
c
I know I could create a lookup table to see if the current combination has already been generated, but I'm wondering if there's a more efficient way to do this?
Thanks in advance!
Code:
function permutate(permutation, addendum) {
if (addendum.length == 0) {
console.log(permutation);
return;
}
for (var i = 0; i < addendum.length; i++) {
permutate(permutation + addendum.charAt(i), addendum.substring(0, i) + addendum.substring(i+1, addendum.length));
}
for (var i = permutation.length; i > 0; i--) {
permutate("", permutation.substring(0, i));
}
}
var str = "abc";
permutate("", str);
output:
abc
ab
a
ba
b
a
acb
ac
a
ca
c
a
a
bac
ba
b
ab
a
b
bca
bc
b
cb
c
b
b
cab
ca
c
ac
a
c
cba
cb
c
bc
b
c
c
I know I could create a lookup table to see if the current combination has already been generated, but I'm wondering if there's a more efficient way to do this?
Thanks in advance!