Reputation: 21
I'm trying to solve a problem with an array of numbers and 3 for loops in Java. It involves figuring out which 3 numbers from the array add up to a specific sum. For this test I used a sum of 9.
int nums[] = {1, 3, 5, 7, 9, 11, 13, 15};
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 7; j++)
for (int y = 0; y <= 7; y++)
if(nums[i] + nums[j] + nums[y] == 9)
System.out.print(i + " " + j + " " + y);
}
The correct answer is 3 3 3 but this output reads:
0 0 30 1 20 2 10 3 01 0 21 1 11 2 02 0 12 1 03 0 0
I know I'm probably nesting the for loops completely wrong but I can't figure out where to put the code blocks without getting rid of one of the variables in the scope of the if statement. Thanks for any help.
Upvotes: 1
Views: 64
Reputation: 20490
Some issues in your code
System.out.print(i + " " + j + " " + y);
instead you want to print the numbers.println
to print everything on a newline1,3,5
The updated code will then be
for (int i = 0; i <= 7; i++) {
for (int j = i+1; j <= 7; j++)
for (int y = j+1; y <= 7; y++)
if( nums[i] + nums[j] + nums[y] == 9)
//Print the numbers on newline
System.out.println(nums[i] + " " +nums[j] + " " + nums[y]);
}
The output will be
1 3 5
If repetition is allowed, then all 3 loops will run from 0 and the answer changes
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 7; j++)
for (int y = 0; y <= 7; y++)
if( nums[i] + nums[j] + nums[y] == 9)
//Print the numbers on newline
System.out.println(nums[i] + " " +nums[j] + " " + nums[y]);
}
The answer will then be
1 1 7
1 3 5
1 5 3
1 7 1
3 1 5
3 3 3
3 5 1
5 1 3
5 3 1
7 1 1
Upvotes: 1
Reputation: 778
You're testing the same values multiple times, i.e. 1+1+7, 1+7+1, 7+1+1 are all being tested. Use for for (int j = i; j <= 7; j++)
and for (int y = j; y <= 7; y++)
. Note that there are multiple answers, not just 3 3 3, if you are allowing values to be used multiple times.
Upvotes: 0
Reputation: 7730
The correct answer is 3 3 3 but this output reads:
No, The correct answer is definitely not 3 3 3
, So if I am not wrong you want to find a triplet which sums up to your test sum, which in this case is 9, So correct answer is 1,3,5
Try this :
for (int i = 0; i <= 7; i++) {
for (int j = i + 1; j <= 7; j++)
for (int y = j + 1; y <= 7; y++)
if (nums[i] + nums[j] + nums[y] == 9)
System.out.print(nums[i] + " " + nums[j] + " " + nums[y]);
}
Running Sample : https://ideone.com/5UAuGv
Upvotes: 0