[R] Breaking out of multiple loops
MacQueen, Don
macqueen1 at llnl.gov
Wed Dec 19 18:43:08 CET 2012
There is a break() function. Does it not do the job?
-Don
--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
On 12/19/12 7:27 AM, "McCloskey, Bryan" <bmccloskey at usgs.gov> wrote:
>Something like this?
>
>n<-1000
>pythag<-function(n){
> for(i in 3:((n-3)/3))
> for(j in (i+1):((n-i)/2))
> if(i^2+j^2==(n-i-j)^2) return(i*j*(n-i-j))
>}
>system.time(print(pythag(n)))
>
>Interesting -- seems to improve speed by ~12%. Not sure if that's
>because stop() has more overhead, or if functions are innately faster
>somehow. Still seems like there should be a way to break out of nested
>loops, though...
>
>-b
>
>On Tue, Dec 18, 2012 at 4:50 PM, Duncan Murdoch
><murdoch.duncan at gmail.com> wrote:
>> On 12-12-18 1:02 PM, McCloskey, Bryan wrote:
>>>
>>> Hey all,
>>>
>>> I'm currently working through the problems at Project Euler -- this
>>> question came up while working on Problem 9
>>> (http://projecteuler.net/problem=9):
>>>
>>> "A Pythagorean triplet is a set of three natural numbers, a < b < c,
>>> for which, a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 9 + 16 = 25 =
>>> 5^2. There exists exactly one Pythagorean triplet for which a + b + c
>>> = 1000. Find the product abc."
>>>
>>> Not too hard:
>>>
>>> n=1000
>>> for(i in 1:floor(n/3))
>>> for(j in (i+1):floor(n/2-i/2))
>>> if(i^2+j^2==(n-i-j)^2) {print(i*j*(n-i-j)); stop()}
>>>
>>> I could just let the for loops finish looping after it finds the
>>> answer, and it would still run in under a second, but the goal of
>>> Project Euler is sort of to see how efficiently (and quickly) you can
>>> solve these problems, so in that spirit I would like to break out of
>>> the for loops early once the answer is found -- hence the call to
>>> stop(). However, this seems "improper", as it throws up an error. Is
>>> there a way to exit out of both for loops with a call to "break" or
>>> similar that would not throw errors (or is it fine the way I've coded
>>> it)? (I realize I could put an "if(i^2+j^2==(n-i-j)^2) break"
>>> statement in the outer loop, but again that's inefficient, as it's
>>> checking that conditional hundreds of times.)
>>>
>>> So is there a way to "cleanly" break out of multiple loops?
>>
>>
>> Put them in a function, and return from the function.
>>
>> Duncan Murdoch
>>
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list