Konstanius EU
Konstanius EU

Reputation: 63

How do I create n amount of nested for loops in Java?

So I have a code which generates all possible strings of a length n (currently 5 in this example) with characters in a list "chars" and executes a certain code once on each string in the end (not included here). How would I condense the code here into code that automatically nests the loops n amount of times and then executes a final code on each result?

            for(String str2: chars) {
            str2 = str1 + str2;
            for(String str3: chars) {
                str3 = str2 + str3;
                for(String str4: chars) {
                    str4 = str3 + str4;
                    for(String str5: chars) {
                        str5 = str4 + str5;
                        for(String str6: chars) {
                            str6 = str5 + str6;
                        }
                    }
                }
            }
        }
    }

Upvotes: 0

Views: 572

Answers (1)

josejuan
josejuan

Reputation: 9566

The simplest way is to use recursion

static void allCombinationsRecursive(String current, String symbols, int level) {
    if(level == 0)
        // no more nested loop
        System.out.println(current);
    else
        // current loop
        for(Character c: symbols.toCharArray())
            // next nested loops
            allCombinationsRecursive(current + c, symbols, level - 1);
}

public static void main(String... args) {
    allCombinationsRecursive("", "ABC", 2);
}

with output

AA
AB
AC
BA
BB
BC
CA
CB
CC

If you need an iterative version, you must carry out the state for every nested loop

static void allCombinationsIterative(String symbols, int levels) {
    // current index for each loop
    int [] index = new int [levels];   // << here any NESTED LEVEL STATE
    // not started
    for(int i = 0; i < levels; i++)
        index[i] = -1;
    // current level is 0
    int level = 0;
    while(level >= 0) {
        // max level reatched?
        if(level == levels) {
            System.out.println(Arrays.stream(index).mapToObj(i -> symbols.substring(i, i + 1)).collect(joining("")));
            level -= 1;
        } else {
            // can we inc this level?
            if (index[level] < symbols.length() - 1) {
                index[level] += 1;
                level += 1;
            } else {
                // back
                index[level] = -1;
                level -= 1;
            }
        }
    }
}

(with the same output)

Note that neither algorithm takes into account what type of algorithm is involved (generating combinations or any other problem).

Upvotes: 1

Related Questions