如何从两个数组中获取所有可能的组合?

2022-09-02 09:36:21

我有两个数组:

String[] operators = {"+", "-", "*"};
int[] numbers = {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
..........
48*24*12*6

这是我尝试过的:

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]);
}

但它只打印:

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

如何解决这个问题?

这不是重复的,因为我不想获取每两对数据,我想获取4对中的每个组合。副本是不同的。


答案 1

使用三重循环:

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]);
        }
    }
}

您基本上想要取运算符向量的交叉积(如果它是向量)。在Java中,这转化为一组三重嵌套的循环。


答案 2

虽然@TimBiegeleisen解决方案就像一个魅力,但它的复杂性可能是一个问题。更好的方法是这样的代码:

static void combinationUtil(
        int[] arr, int n, int r, int index, int[] data, int i) {
    // Current combination is ready to be printed, print it 
    if (index == r) {
        for (int j = 0; j < r; j++)
            System.out.print(data[j] + " ");
        System.out.println("");
        return;
    }

    // When no more elements are there to put in data[] 
    if (i >= n)
        return;

    // current is included, put next at next location 
    data[index] = arr[i];
    combinationUtil(arr, n, r, index + 1, data, i + 1);

    // current is excluded, replace it with next (Note that 
    // i+1 is passed, but index is not changed) 
    combinationUtil(arr, n, r, index, data, i + 1);
}
// The main function that prints all combinations of size r 
// in arr[] of size n. This function mainly uses combinationUtil() 
static void printCombination(int arr[], int n, int r) {
    // A temporary array to store all combination one by one 
    int data[] = new int[r];

    // Print all combination using temprary array 'data[]' 
    combinationUtil(arr, n, r, 0, data, 0);
}

来源:GeeksForGeeks和我的IDE:)