Reputation: 23
Ok, I stripped this code as much as I could. The solution I'm seeking is probably simple. Here it goes:
import java.util.Arrays;
public class App {
public static void main(String[] args) {
for (int k = 1; k < 9; k++) {
for (int p = 1; p < 9; p++) {
for (int i = 1; i < 9; i++) {
if (k + p + i == 9) {
System.out.println("The 3 numbers that give the sum of 9 are: " + k + p + i);
}
}
}
}
}
}
I'm trying to find all combinations of 3 numbers that sum up to number 9. I've done this through 3 for loops as you can see in the code but the problem is that the result also displays same numbers but in different order. For example: 117 and 711. I don't want that, I just want one combination of the same numbers. What is the simplest solution to this?
Upvotes: 1
Views: 50
Reputation: 11131
As someone else already said, one possible right answer is
for (int k = 1; k < 9; k++)
for (int p = k + 1; p < 9; p++)
for (int i = p + 1; i < 9; i++)
if (k + p + i == 9)
System.out.println(""+k + p + i);
But do you really understand why?
Imagine you're looking for combinations of 2 numbers that sum up to 9. You could use just two index, say k and p, and imagine your set of couples as points on a 2D plane
You can easily spot the points you're interested in, the ones that sums up to 9, here represented as blue dots:
Here you have exactly 10 possible solutions to your [semplified] problem (0,9), (1,8), (2,7), (3,6), (4,5), (5,4), (6,3), (7,2), (8,1), (9,0), and every solution has a twin solution you want to get rid of.
How can you do that? By declaring int p = k + 1. This, from the point of view of our plane, means excluding half of the portion of possible solutions from your search:
cutting off the red area and, consequentely, duplicate solutions. Hence, the solution for the simplified problem would be (including 0 and 9)
for (int k = 0; k <= 9; k++)
for (int p = k + 1; p <= 9; p++)
if (k + p == 9)
System.out.println(""+k + p);
and the output would be
09
18
27
36
45
Upvotes: 1
Reputation: 12196
Then you should limit your inner loops.
Solution: p < 9
should be p <= k
and i < 9
should be i <= p
Code:
public static void main(String[] args) {
for (int k = 1; k < 9; k++) {
for (int p = 1; p <= k; p++) {
for (int i = 1; i <= p; i++) {
if (k + p + i == 9) {
System.out.println("The 3 numbers that give the sum of 9 are: " + k + p + i);
}
}
}
}
}
Upvotes: 2
Reputation: 4453
Change your main method to this..
for (int k = 1; k < 9; k++) {
for (int p = k + 1; p < 9; p++) {
for (int i = p + 1; i < 9; i++) {
if (k + p + i == 9) {
System.out.println("The 3 numbers that give the sum of 9 are: " + k + p + i);
}
}
}
}
Upvotes: 0