Loops/Nested: Difference between revisions
Content added Content deleted
(Frink) |
(Added AppleScript.) |
||
Line 255: | Line 255: | ||
12 20 |
12 20 |
||
</pre> |
</pre> |
||
=={{header|AppleScript}}== |
|||
AppleScript has <tt>exit repeat</tt> to break out of a single loop prematurely, but nothing specifically for nested loops. So either <tt>exit repeat</tt> must be used twice … |
|||
<lang applescript>on loopDemo(array, stopVal) |
|||
set out to {} |
|||
repeat with i from 1 to (count array) |
|||
set inRow to item i of array |
|||
set outRow to {} |
|||
repeat with j from 1 to (count inRow) |
|||
set n to item j of inRow |
|||
set end of outRow to n |
|||
if (n = stopVal) then exit repeat # <-- |
|||
end repeat |
|||
set end of out to outRow |
|||
if (n = stopVal) then exit repeat # <-- |
|||
end repeat |
|||
return out |
|||
end loopDemo</lang> |
|||
… or of course one or both loops can be specified to terminate at the critical juncture anyway … |
|||
<lang applescript>on loopDemo(array, stopVal) |
|||
set out to {} |
|||
repeat with i from 1 to (count array) |
|||
set inRow to item i of array |
|||
set len to (count inRow) |
|||
set n to beginning of inRow |
|||
set outRow to {n} |
|||
set j to 2 |
|||
repeat until ((j > len) or (n = stopVal)) # <-- |
|||
set n to item j of inRow |
|||
set end of outRow to n |
|||
set j to j + 1 |
|||
end repeat |
|||
set end of out to outRow |
|||
if (n = stopVal) then exit repeat # <-- |
|||
end repeat |
|||
return out |
|||
end loopDemo</lang> |
|||
… or, with the process in a dedicated handler, it can be returned from directly at any point: |
|||
<lang applescript>on loopDemo(array, stopVal) |
|||
set out to {} |
|||
repeat with i from 1 to (count array) |
|||
set inRow to item i of array |
|||
set outRow to {} |
|||
repeat with j from 1 to (count inRow) |
|||
set n to item j of inRow |
|||
set end of outRow to n |
|||
if (n = stopVal) then return out & {outRow} # <-- |
|||
end repeat |
|||
set end of out to outRow |
|||
end repeat |
|||
return out |
|||
end loopDemo</lang> |
|||
Demo: |
|||
<lang applescript>local array, stopVal, row |
|||
set array to {} |
|||
set stopVal to 20 |
|||
repeat 10 times |
|||
set row to {} |
|||
repeat 10 times |
|||
set end of row to (random number from 1 to stopVal) |
|||
end repeat |
|||
set end of array to row |
|||
end repeat |
|||
loopDemo(array, stopVal) -- Any of the handlers above.</lang> |
|||
{{output}} |
|||
<lang applescript>{{15, 8, 9, 8, 9, 9, 10, 16, 3, 6}, {11, 3, 14, 18, 17, 1, 16, 15, 14, 7}, {4, 20}}</lang> |
|||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |