Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String Permutations

Status
Not open for further replies.

mratx

Programmer
Joined
Sep 17, 2009
Messages
4
Location
US
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:
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!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top