Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of nested for loops in Julia

I have tried to break out of nested loops in a quite ineffective way:

BreakingPoint = false
a=["R1","R2","R3"]
b=["R2","R3","R4"]
for i in a
  for j in b
    if i == j
      BreakingPoint = true
      println("i = $i, j = $j.")
    end
    if BreakingPoint == true; break; end
  end
  if BreakingPoint == true; break; end
end

Is there an easier way to do that? In my actual problem, I have no idea about what are in arrays a and b, apart from they are ASCIIStrings. The array names (a and b in sample code) are also auto-generated through meta-programming methods.

like image 321
zyc Avatar asked Sep 30 '16 16:09

zyc


People also ask

How do I get out of a nested loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do I break out of all for loops?

Method 1: Using the return statement Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops.

Does continue break out of nested for loop?

Break out of nested loops with else and continueYou can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed.


2 Answers

You can do one of two things

have the loop statement (if thats what its called) in a multi outer loop

for i in a, j in b
    if i == j
        break
    end 
end 

which is clean, but not always possible

I will be crucified for suggesting this, but you can use @goto and @label

for i in a
    for j in b
        if i == j
            @goto escape_label
        end
    end
end

@label escape_label

If you go with the @goto/@label way, for the sake of the people maintaining/reviewing the code, document your use properly, as navigating code with labels is breathtakingly annoying

For the discussion on the multi-loop break, see this

like image 161
isebarn Avatar answered Oct 13 '22 06:10

isebarn


Put the 2D loop into a function, and do an early return when you want to break.

like image 22
Carcigenicate Avatar answered Oct 13 '22 06:10

Carcigenicate