Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the two arrays:

String[] operators = {"+", "-", "*"};
int[] numbers = {48, 24, 12, 6};

And I want to get all possible combination in a String format like this:

48+24+12+6
48+24+12-6
48+24+12*6
48+24-12+6
48+24-12-6
48+24-12*6
..........
48*24*12*6

This what I have tried:

for (int i = 0; i < operators.length; i++) {
    System.out.println(numbers[0] + operators[i] + numbers[1] +
            operators[i] + numbers[2] + operators[i] + numbers[3]);
}

But it only prints:

48+24+12+6
48-24-12-6
48*24*12*6

How to solve this?

This is not a duplicate because I don't want to get every two pairs of data, I want to get every combination in 4 pairs. The duplicate is different.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
450 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use a triple loop:

for (int i=0; i < operators.length; ++i) {
    for (int j=0; j < operators.length; ++j) {
        for (int k=0; k < operators.length; ++k) {
            System.out.println(numbers[0] + operators[i] + numbers[1] + operators[j] +
                numbers[2] + operators[k] + numbers[3]);
        }
    }
}

You essentially want to take the cross product of the operators vector (if it were a vector). In Java, this translates to a triply-nested set of loops.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...