如何在Java中获取Integer arrayList的组合的集合?

时间:2018-06-24 01:42:04

标签: java arraylist combinations

我的目标是在ArrayList中以固定的预定义长度找到所有可能的项目组合。例如,如果我的ArrayList称为arr并包含$.ajax({ url: '/Home/DoMyAction', type: 'POST', data: { "var1": "Hello", "var2":"World!"}, datatype: "json", contenttype: "application/json; charset=utf-8", success: function (result) { if (!result.Status) // Display error message. }, error: function () { } }); ,则预定义大小r = 2的期望输出将是:

<1, 2, 3>

这是我发现的打印所需输出的代码。我的问题是我需要定义一个返回值类型ArrayList,该值保存方法的输出。此外,我的输入类型也是<1,2> <1,3> <2,3> ,而不是数组,这对我来说使它变得更加复杂,因为然后我首先需要将值转换为原始类型int。

ArrayList<Integer>

1 个答案:

答案 0 :(得分:2)

ArrayList在内部由数组备份,因此将当前基于array的实现转换为ArrayList应该是合理的。在arrays中,您可以使用[]运算符来索引array中的元素,而使用ArrayList的并行操作是getset。另外,您可能想阅读Autoboxing and Unboxing。使用Lists的可能实现:

static void combinationUtil(List<Integer> list, List<Integer> data, int start, int end, int index, int r) {
    // Current combination is ready to be printed, print it
    if (index == r) {
        for (int j = 0; j < r; j++)
            System.out.print(data.get(j) + " ");
        System.out.println("");
        return;
    }

    // replace index with all possible elements. The condition
    // "end-i+1 >= r-index" makes sure that including one element
    // at index will make a combination with remaining elements
    // at remaining positions
    for (int i = start; i <= end && end - i + 1 >= r - index; i++) {
        data.set(index, list.get(i));
        combinationUtil(list, data, i + 1, end, index + 1, r);
    }
}

// The main function that prints all combinations of size r
// in list of size n. This function mainly uses combinationUtil()
static void printCombination(List<Integer> list, int n, int r) {
    // A temporary array to store all combination one by one
    List<Integer> data = new ArrayList<>(Collections.nCopies(r, 0));

    // Print all combination using temporary array 'data'
    combinationUtil(list, data, 0, n - 1, 0, r);
}

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    int r = 3;
    int n = list.size();
    printCombination(list, n, r);
}