I think you need a backtracking algorithm. But then you replace your nested loops with recursion.
I do not want to post links here, as moderators do not like it.
Look at the “eight queen puzzle” (you can do it on Google), you get my idea.
I know this idea works, since I asked this very question (which you have) for me in many cases, and I have applied it several times successfully.
Here is a small example (I modified it since the previous one was a bit complicated).
public class Test001 { public static void main(String[] args) { loop(0, 5, 10); } private static void loop(int level, int max_level, int size){ if (level > max_level) return; for (int i=0; i<size-level; i++){ System.out.println("Now at level: " + level + " counter = " + i); loop(level + 1, max_level, size); } } }
But it still uses recursion.
peter.petrov
source share