Reputation: 185
Is there an efficient way to run nested for loops, avoiding any of the counters having the same value. Obviously, I could run some if statements, as below, but is there a more efficient way?
for i = 1 to 20:
for j = 1 to 20:
if (i == j):
continue
else:
for k = 1 to 20:
if (i == k) or (j == k):
continue
else:
do something useful with these different numbers
EDIT: The variables are not interchangeable, so [2, 1, 0] is different to [0, 1, 2]. The "do something useful" will be about 6 numerical checks on the numbers, involving adding, squaring, and square rooting them.
Thanks, and sorry about the possibly unusual pseudocode (and the constant editing).
Upvotes: 2
Views: 3512
Reputation: 1311
The only thing you can possibly save efficiency on here is your looping logic. Assuming you implement it correctly, there are always going to be 20*19*18 operations to do.
You won't be able to find a solution with the limited detail you have given. What is the 'something useful'?
If it turns out that for that operation, the individual values of i, j, and k do not matter, just the combination of 3 numbers, then yes you can make significant efficiency savings. With your current set up, you will pass in the (i,j,k) values (1, 2, 3) (1,3,2) (2,1,3) (2,3,1) etc...
So if you are looking for combinations, not permutations, you can modify it to reduce effort by a fact of 6 quite easily, by starting j one bigger than i, and k one bigger than j in each internal loop.
Upvotes: 0
Reputation: 7237
That looks like the most efficient way you can do it. What's wrong with how you have it?
I'm just going to ignore the part where I can't think of any reason to ever need to do this.... so if you have a specific case please share? Unless your trying to compare an item to all other items in a list that isn't itself I guess?
which could be done as
list = {1,2,3,4,1,2,3,4} \\where list[0] will return 1, and list.size() will return 8
for(int i = 0; i < list.size()-1; i++){
for(int j = i + 1; j < list.size(); j++){
System.out.println(list[i] + "," + list[j]);
}
}
That way you dont repeat comparisons between things you have already compared.
For three nests
list = {1,2,3,4,1,2,3,4} \\where list[0] will return 1, and list.size() will return 8
for(int i = 0; i < list.size()-2; i++){
for(int j = i + 1; j < list.size()-1; j++){
for(int k = j + 1; j < list.size(); k++){
System.out.println(list[i] + "," + list[j] + "," + list[k]);
}
}
Upvotes: 1