Java – Find and print the solution of x1+x2+x3=num

Find and print the solution of x1+x2+x3=num… here is a solution to the problem.

Find and print the solution of x1+x2+x3=num

I need to write a recusive function to take an integer num and return the solution of the equation: x1 + x2 + x3 = num, where x1, x2, x3 are numbers between 1-10, the method should print all solutions.

For example, if num=3, then the method will print 1+1+1 and will return 1

If num=5, the method returns 6 and prints:

1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1

If num<3 or num>30, the method returns 0

The method should be recursive and do not use loops. Global variables are not allowed. Lists are also not allowed.

Here is my code, it works fine but it also prints duplicates, for num=5 it prints:

3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3

Here is my code :

public static void main(String[] args) {
    System.out.println("num of solutions: "+solutions(5));

}

public static int solutions(int num) 
{

if (num < 3 || num > 30)
        return 0;

return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
    if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10|| x3 < 1 || x3 > 10)
        return 0;
    if (x1 + x2 + x3 > num)
        return 0;       
    if (x1 + x2 + x3 == num)
    {
        System.out.println(x1 + " + " + x2 + " + " + x3);
        return 1;
    }           
    return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);

}

How do I get the desired output without duplicates?

Solution

The reason you get duplicates is that solutions(1,2,1)

and solutions(2,1,1) both lead you to 2 + 2 + 1.

An easy way not to repeat three digits is to go from 111 to 10, 10, 10 as if it were a decimal integer:

private static int solutions(int num, int x1, int x2, int x3)
{
  if (x1 > 10 || x1 > num)
    return 0;
  if (x2 > 10 || x1+x2 > num)
    return solutions(num, x1+1, 1, 1);
  if (x3 > 10 || x1+x2+x3 > num)
    return solutions(num, x1, x2+1, 1);

int me = 0;
  if (x1+x2+x3 == num) {
    System.out.printf("%d + %d + %d\n", x1, x2, x3);
    me=1;
  }
  return me + solutions(num, x1, x2, x3+1);
}

This mimics the approach of searching the entire space by pruning, but a more efficient solution can search only x1 and x2 and set x3=num -x1-x2

Related Problems and Solutions