Djordje Ivanovic February 2016

How to get all possible combinations of substrings?

I have a String of following structure: A1(N1,N2,N3)P4(O3,O5)Y1.

How to get all combinations? The rule is that options inside parenthesis should not go together. For this example the output should be:

A1N1P4O3Y1,
A1N2P4O3Y1,
A1N3P4O3Y1,
A1N1P4O5Y1,
A1N2P4O5Y1,
A1N3P4O5Y1.

There can be parenthesis, but it can be without it. Another example:

N3P5(L1,L2)Q1, output should be:

N3P5L1Q1,
N3P5L2Q1. 

Anyone with elegant solution?

Answers


andrucz February 2016

The main idea is to transform a string input into a StringTemplate that holds parts, that can be a single string or a group of strings.

For each part, a iterator is created. While some iterator can go next, update a string array that holds current part values and reset all iterators of parts that come before the part that changed. Feel free to clear repeated code and add nested groups support and syntax verifications if needed.

private static StringTemplate parse(String string) {

    List<StringPart> parts = new ArrayList<StringPart>();

    boolean insideGroup = false;
    StringBuilder currentToken = new StringBuilder();

    List<LiteralPart> groupParts = new ArrayList<LiteralPart>();

    for (int i = 0; i < string.length(); i++) {
        char ch = string.charAt(i);

        if (ch == '(') {

            if (currentToken.length() != 0) {
                parts.add(new LiteralPart(currentToken.toString()));
                currentToken.delete(0, currentToken.length());
            }

            insideGroup = true;

        } else if (ch == ')') {

            if (insideGroup) {

                if (currentToken.length() != 0) {
                    groupParts.add(new LiteralPart(currentToken.toString()));
                    currentToken.delete(0, currentToken.length());
                }

                parts.add(new CompositePart(groupParts));
                groupParts.clear();
                insideGroup = false;

            } else {
                currentToken.append(ch);
            }

        } else if (ch == ',') {

            if (insideGroup) {

                if (currentToken.length() != 0) {
                    groupParts.add(new LiteralPart(currentToken.toString()));
                    currentToken.delete(0, currentToken.length());
                }

            } else {
                currentToken.append(ch);
            }

        } else {
            currentToken.append(ch);
        }
  

Post Status

Asked in February 2016
Viewed 1,480 times
Voted 12
Answered 1 times

Search




Leave an answer