Popular Posts

Wednesday, February 2, 2011

Combination of a string

Algorithm :

Step 1: Add the String to the combination results.
Step 2: If the String has just one character in it,
then stop the current line of execution.
Step 3: Create new sub-words from the String by removing one letter at a time.
If the String is "ABCD", form sub-words like "BCD", "ACD", "ABD", "ABC"
Step 4: For each of the sub-word, go to Step 1


    Java program :
     import java.util.HashSet;
    import java.util.Set;

    /**
    * A simple program that generates all possible combinations for a given String
    * using recursion.
    */
    public class StringCombinations {
    // A set to hold the generated combination results.
    private Set<String> combinations = new HashSet<String>();

    /**
    * The constructor.
    *
    * Simply makes a call to the generate method to generate all the possible
    * combinations of the String "wxyz"
    */
    public StringCombinations(String sInputString) {
    generate(sInputString);
    System.out.println("*** Generated " + combinations.size()
    + " combinations ***");
    System.out.println(combinations);
    }

    /**
    * The recursive method does the work of generating all the possible
    * combinations for a given String.
    */
    public void generate(String word) {
    // Add this word to our combination results set
    combinations.add(word);

    // If the word has only one character we break the recursion
    if (word.length() == 1) {
    combinations.add(word);
    return;
    }
    // Go through every position of the word
    for (int i = 0; i < word.length(); i++) {
    // Remove the character at the current position
    // all call this method with that String (Recursion!)
    generate(word.substring(0, i) + word.substring(i + 1));
    }
    }

    /**
    * Entry point to this program. Instantiates the StringCombinations program.
    *
    */
    public static void main(String args[]) {
    String sInputString = "abcd";
    new StringCombinations(sInputString);
    }

    }

    No comments:

    Post a Comment