Bipon Roy
Bipon Roy

Reputation: 63

How to break from a nested for loop to its outermost loop?

I am attempting to solve a problem where I must find 3 numbers which add up to the number n for t number of cases.

Here are the restrictions

Given four numbers N,A,B,C, find three numbers that sum up to N, with the following restrictions:

The first number must be an integer between 0 and A (inclusive)
The second number must be an integer between 0 and B (inclusive)
The third number must be an integer between 0 and C (inclusive)

I currently have a working solution, however my solution prints out every single possible answer instead of just the very first one which is the correct answer. How am I able to return to my very first for-loop once finding the very first solution?

Here is the link to the problem: https://dmoj.ca/problem/ac19p1

Here is my code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        int t = input.nextInt();

        for(int i=0;i<t;i++){

            int n = input.nextInt();
            int a = input.nextInt();
            int b = input.nextInt();
            int c = input.nextInt();

            if(n<0){
                System.out.println("-1");
            }
            else{
                for(int one=0; one<(a+1); one++){
                    for(int two=0; two<(b+1); two++){
                        for(int three=0; three<(c+1); three++){
                            if((one+two+three)==n){
                                System.out.println(one+" "+two+" "+three);
                                break;
                            }
                        }
                    }
                }

            }
        }
    }
}

Input:

1
100
100
53 
49

Correct Solution:

0 51 49

My current solution:

0 51 49
0 52 48
0 53 47
1 50 49
1 51 48
1 52 47
1 53 46
2 49 49
2 50 48
...

Upvotes: 0

Views: 49

Answers (1)

markspace
markspace

Reputation: 11020

Use a label.

      endItAll:
            for(int one=0; one<(a+1); one++){
                for(int two=0; two<(b+1); two++){
                    for(int three=0; three<(c+1); three++){
                        if((one+two+three)==n){
                            System.out.println(one+" "+two+" "+three);
                            break endItAll;
                        }
                    }
                }
            }

More info in the tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Upvotes: 2

Related Questions