Friday, December 30, 2011

Combination of all the possible characters in the string

Question: Write an algorithm to print all possible combinations of characters in a string.
Note : By combination it means number of different strings possible taking 1 or 2 ...or n characters from string, so we dont have to worry about various character permutation. So for beta, when you get eta, you don't have to get its anagrams like ate, tae etc. For a string of length n, there are nCn + nCn-1 + ... + nC1 combinations. For string abc, there are 1 + 3 + 3 = 7 combinations.
nC1 - a, b, c
nC2 - ab, bc, ca
nC3 - abc

Answer: Any thoughts? One thing is for sure, we can definitely use some recursive logic here. Let’s approach this problem methodically. Since we need to generate combinations, we can start with a single character and then continue to add a character to combinations we have seen so far. Let’s use "abc" as an example.

static void combine(String instr, StringBuffer outstr, int index)
{
    for (int i = index; i < instr.length(); i++)
    {
       outstr.append(instr.charAt(i));
       System.out.println(outstr);
       combine(instr, outstr, i + 1);
       outstr.deleteCharAt(outstr.length() - 1);//reduce outstr by 1 char from end
    }
}

Now to call this function:
combine("abc", new StringBuffer(), 0);

Better solution
Though solution is good, it will not work when 1 or more characters are repeated. So here is other solution:
static Set getCombinations(String instr, StringBuffer outstr, int index){
    Set combinations = new HashSet();
    for (int i = index; i < instr.length(); i++)
    {
        outstr.append(instr.charAt(i));
        combinations.add(outstr.toString());
        combinations.addAll(getCombinations(instr, outstr, i + 1));
        outstr.deleteCharAt(outstr.length() - 1);
    }
    return combinations;
}

Calling the function:
Set comb = getCombinations(ms, new StringBuffer(), 0);
System.out.println(comb.toString());

0 comments:

Post a Comment