0

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;
                        }
                    }
                }
            }
        }
    }
  • 1
    just use recursion. https://www.javatpoint.com/recursion-in-java#:~:text=Recursion%20in%20java%20is%20a,compact%20but%20complex%20to%20understand. – D. Mateescu Jan 21 '22 at 11:03
  • 3
    You should really look for better approach than this to generate all possible strings. – kiner_shah Jan 21 '22 at 11:04
  • This is for a hashing algorithm, so it needs to go through them all. – Konstanius EU Jan 21 '22 at 11:08
  • It also cannot use recursion, as the variables in it need to be saved separately on each "level" of the nest – Konstanius EU Jan 21 '22 at 11:10
  • Basically a solved problem, see https://stackoverflow.com/questions/2799078/permutation-algorithm-without-recursion-java for example. – GhostCat Jan 21 '22 at 11:22
  • "It also cannot use recursion" this doesn't preclude recursion, you just need a way to update the "variables", e.g. by storing them in a list. – Andy Turner Jan 21 '22 at 11:29

1 Answers1

1

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).

josejuan
  • 9,338
  • 24
  • 31