Java – Returns the solution of the equation x1 + x2 + x3 = num

Returns the solution of the equation x1 + x2 + x3 = num… here is a solution to the problem.

Returns the solution of the equation x1 + x2 + x3 = num

I’m trying to write a recursive method that takes a positive integer num argument and returns the solution of the equation

x1 + x2 + x3 = number

When three x’s are positive integers between 1 and 10.
The method should also print out the solutions, each on a separate line. The print order does not matter.

I tried:

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

public static int solutions (int num)
{
    if (num < 3 || num > 30) {
        return 0;
    }
    return solutions (1, 1, 1, 0, num);

}

The problem is that I repeat the result,

the problem is that I get the duplicate result, e.g. num = 5, and I get:

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

Replace

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

How can I avoid repeating it twice?

Solution

Here’s how I handle it :

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

public static int solutions(int num) 
{
    if (num < 3 || num > 30)
        return 0;
    else
        return solutions(num, 1, 1, 1);
}

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

Related Problems and Solutions