Monday, June 3, 2024
190
rated 0 times [  192] [ 2]  / answers: 1 / hits: 31130  / 12 Years ago, tue, august 21, 2012, 12:00:00

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:



A
B
C
AB
AC
ABC


I could use loops like so:



for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}


But I don't know the length of the string, so wouldn't know how many loops to use.



Any ideas?



Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.



This is not homework. It's for a program to solve a 'lights-out' type game.


More From » combinations

 Answers
23

This is what I ended up using.



var combinations = function (string)
{
var result = [];

var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}

for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}

return result;
}

[#83519] Sunday, August 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;