二维数组列表的排列 [英] Permutation of a 2 dimensional arraylist
问题描述
我正在尝试制作一个二维数组列表,该列表中填充了递归的每个可能的组合,比如 1,2,3,4.没有加倍.
I'm trying to make a 2 dimensional array list that is filled with every possible combination of lets say 1,2,3,4 recursively. with no double ups.
例如.
1,0,0
2,0,0
3,0,0
4,0,0
1,2,0
1,3,0
1,4,0
1,2,3
等等...
for example.
1,0,0
2,0,0
3,0,0
4,0,0
1,2,0
1,3,0
1,4,0
1,2,3
etc...
到目前为止我有
//this gives me all my numbers
for(int i =0;i<arraySize;i++)
index[i] = i;
// and is the part that make the combinations
for(int i = 0;i<arraySize;i++){
for(int x = 0;x<k;x++)
combinations.get(i).set(x, index[i]);
我也不想打印结果我想将结果存储在二维数组中
Also I'm not trying to print the result I want to store the result in a 2 dimensional array
推荐答案
另一个非递归选项.我用词"表示(部分)排列,用符号"表示数字:
Another, non-recursive option. I use "words" for (partial) permutations and "symbols" for numbers:
/**
* Expands the set of existing words by adding non-repeated symbols to their right
* @param symbols to choose from
* @param existing words (may include the empty word)
* @param expanded result
*/
public static void expand(ArrayList<Integer> symbols,
ArrayList<ArrayList<Integer>> existing,
ArrayList<ArrayList<Integer>> expanded) {
for (ArrayList<Integer> prev : existing) {
Integer last = prev.isEmpty() ? null : prev.get(prev.size()-1);
for (Integer s : symbols) {
if (last == null || s > last) {
ArrayList<Integer> toAdd = new ArrayList<>(prev);
toAdd.add(s);
expanded.add(toAdd);
}
}
}
}
public static void main(String[] args) {
ArrayList<Integer> symbols = new ArrayList<>(
Arrays.asList(new Integer[]{1, 2, 3, 4}));
ArrayList<ArrayList<Integer>> prev = new ArrayList<>();
ArrayList<ArrayList<Integer>> next = new ArrayList<>();
ArrayList<ArrayList<Integer>> aux;
ArrayList<ArrayList<Integer>> output = new ArrayList<>();
// add empty
prev.add(new ArrayList<Integer>());
// expand empty, then expand that expansion, and so on and so forth
for (int i=0; i<symbols.size(); i++) {
expand(symbols, prev, next);
output.addAll(next);
aux = prev; prev = next; next = aux;
next.clear();
}
// print result (note: only for debugging purposes)
for (ArrayList<Integer> o : output) {
for (int i : o) System.out.print(i); System.out.println();
}
}
并且输出与原始问题匹配(这不是似乎要求实际排列,至少根据提供的示例):
And the output matches the original question (which does not seem to be asking for actual permutations, at least according to the provided example):
1
2
3
4
12
13
14
23
24
34
123
124
134
234
1234
这篇关于二维数组列表的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!