java get all possible variants (positive and negative) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of java get all possible variants (positive and negative) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Lets say I got a row of number “1 2 3 4” I need to get all possible values

1+2+3+4
1+2+3-4
1+2-3+4
1+2-3-4
...
-1-2-3-4

tried to write a recursion but it kinda works with “1 2” and “1 2 3”

it should work with 1 2 3 … n

checkSum(0, list.size(), list);

private void checkSum(int start, int end, List<Long> list) {

    for (int i = start; i < end; i++){
        list.set(i, list.get(i) * (-1L));
        printLine(list);
        checkSum(i+2, end, list);
    }
}

private void printLine(List<Long> list) {
    for (int i = 0; i < list.size(); i++) {
        if (i > 0)
            if (list.get(i) > 0L)
                System.out.print("+");
        System.out.print(String.valueOf(list.get(i)));
    }
    System.out.println();
}

Answer

One of a billion ways of doing it below…

public class Thingy {

    public static void main(String[] args) {
        printAll(0, 0, Arrays.asList(1L, 2L, 3L, 4L), "TEST1> ");
        printAll(0, 0, Arrays.asList(5L, 6L, 3L, 8L, 9L), "TEST2> ");
    }

    private static void printAll(int i, long accumulator, List<Long> source, String output) {
        if(i >= source.size()) {
            System.out.println(output + " = " + accumulator);
        } else {
            long n = source.get(i);
            printAll(i + 1, accumulator + n, source, output + " + " + n);
            printAll(i + 1, accumulator - n, source, output + " - " + n);
        }
    }
}

Output…

TEST1>  + 1 + 2 + 3 + 4 = 10
TEST1>  + 1 + 2 + 3 - 4 = 2
TEST1>  + 1 + 2 - 3 + 4 = 4
TEST1>  + 1 + 2 - 3 - 4 = -4
TEST1>  + 1 - 2 + 3 + 4 = 6
TEST1>  + 1 - 2 + 3 - 4 = -2
TEST1>  + 1 - 2 - 3 + 4 = 0
TEST1>  + 1 - 2 - 3 - 4 = -8
TEST1>  - 1 + 2 + 3 + 4 = 8
TEST1>  - 1 + 2 + 3 - 4 = 0
TEST1>  - 1 + 2 - 3 + 4 = 2
TEST1>  - 1 + 2 - 3 - 4 = -6
TEST1>  - 1 -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EST2>  - 5 - 6 - 3 - 8 - 9 = -31
We are here to answer your question about java get all possible variants (positive and negative) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji