Java - ArrayList 元素的排列(整数) - 无法使其正常工作 [英] Java - Permutation of ArrayList elements (Integer) - Can't get it to work properly
问题描述
我一直在四处寻找以解决我的问题.我解决了很多问题,但这个问题仍然困扰着我 :S 我已经很长时间没有接触 Java 编程(一般编程)了,所以请理解那里!;)
I've been looking around quite a bit to solve my issue. I got many problems solved but this one is still haunting me :S It's been a long time I haven't touch Java programming (programming in general) so be understanding out there! ;)
我的目标是从整数数组中获得所有可能的组合.当我使用以下代码应用于整数 {1, 2, 3, 4} 的测试数组时,我希望有:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
2 1 3 4
2 1 4 3
(...)
但这是我得到的
1 2 3 4
1 2 3 4 4 3
1 2 3 4 4 3 3 2 4
My goal is to get all the combination possible out of an array of integers. When I use the following code, applied to the test array of integer {1, 2, 3, 4}, I expect to have:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
2 1 3 4
2 1 4 3
(...)
but here is what I get
1 2 3 4
1 2 3 4 4 3
1 2 3 4 4 3 3 2 4
有没有人有线索、建议甚至解决方案?提前致谢!
Does anybody have a clue, a suggestion or even a solution? Thanks in advance!
public class Calculation{
(...)
public void Permute(ArrayList<Integer> soFar,ArrayList<Integer> rest){
if(rest.isEmpty()) this.fillMatrice(convertIntegers(soFar)); // there it goes in a previously created arrow of int
else{
for(int k=0;k<rest.size();k++){
ArrayList<Integer> next=new ArrayList<Integer>();
next=soFar;
next.add(rest.get(k));
ArrayList<Integer> remaining=new ArrayList<Integer>();
List<Integer> sublist = rest.subList(0, k);
for(int a=0;a<sublist.size();a++) remaining.add(sublist.get(a));
sublist = rest.subList(k+1,rest.size());
for(int a=0;a<sublist.size();a++) remaining.add(sublist.get(a));
Permute(next,remaining);
}
}
}
public static ArrayList<Integer> convertArray(int[] integers){
ArrayList<Integer> convArray=new ArrayList<Integer>();
for(int i=0;i<integers.length;i++) convArray.add(integers[i]);
return convArray;
}
public static int[] convertIntegers(List<Integer> integers){
int[] ret = new int[integers.size()];
for(int i=0;i<ret.length;i++) ret[i]=integers.get(i).intValue();
return ret;
}
public Calculation() {
(...)
ArrayList<Integer> soFar=new ArrayList<Integer>();
int[] test={1,2,3,4};
Permute(soFar,convertArray(test));
}
推荐答案
你可以试试Recursion
来解决这个问题:
You can try Recursion
to solve this issue:
public static void printPermutations(int[] n, int[] Nr, int idx) {
if (idx == n.length) { //stop condition for the recursion [base clause]
System.out.println(Arrays.toString(n));
return;
}
for (int i = 0; i <= Nr[idx]; i++) {
n[idx] = i;
printPermutations(n, Nr, idx+1); //recursive invokation, for next elements
}
}
可以从此链接获得更多信息:组合学:生成所有状态"——数组组合
More info can be had from this link: Combinatorics: generate all "states" - array combinations
您也可以在这里复制相同的逻辑.
You can replicate the same logic here as well.
这篇关于Java - ArrayList 元素的排列(整数) - 无法使其正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!