Skip to content
Advertisement

How to get all one and two letter combinations in order from a word?

For example, there is a line

String str = "program";

It is necessary to get all possible combinations, such as:

  • p-r-o-g-r-a-m
  • p-r-o-g-r-am
  • p-r-o-g-ra-m
  • pr-og-r-am

and so on.

How do I do this in java? Or at least tell me a general algorithm (with an example)?

It is not a problem to break the deadline, at least one character at a time, at least two, for example

for (int i = 0; i <str.length () - 1; i = i +2) {
             String strTemp = str.charAt (i) + "" + str.charAt (i + 1);
               System.out.println (strTemp);
}

But how to get (bypass) all possible combinations of one and two is not clear how to program.

Advertisement

Answer

you can do this using recursive programming:

public Set<String> combination(String str){
    final Set<String> results = new HashSet<>();
    if(str.length() == 0)
        return results;
    if(str.length() == 1){
        results.add(str);
        return results;
    }
    if(str.length() == 2){
        results.add(str.charAt(0) + "-" + str.charAt(1));
        results.add(str);
        return results;
    }
    String head = str.substring(0, 1);
    final Set<String> remaining = combination(str.substring(1));
    remaining.forEach(s -> {
        int i = s.indexOf("-");
        if(i == 1){
            results.add(head + s);
            results.add(head + "-" + s);
        } else if(s.length() == 2){
            results.add(head + "-" + s);
        } else if(i == 2){
            results.add(head + "-" + s);
        }
    });
    return results;
}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement