複現這個例子之前先要導入依賴:
<dependency>
<groupId>org.raistlic.lib</groupId>
<artifactId>commons-core</artifactId>
<version>1.4</version>
</dependency>
運作如下代碼:
package com.zhang.arrangementselect;
import org.junit.jupiter.api.Test;
import org.raistlic.common.permutation.Permutation;
import java.util.*;
/**
* @description:産生所有的組合
* @author: zhangyu
* @create: 2019-09-26 14:18
*/
public class GenerateTwoNumber {
@Test
public void getPermutationFun() {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<List<String>> newList = new ArrayList<>();
for (List<String> p : Permutation.of(list)) {
System.out.println(p);
newList.add(p);
}
System.out.println(newList);
}
}
返現運作結果:
[a, b, c]
[a, c, b]
[b, a, c]
[b, c, a]
[c, a, b]
[c, b, a]
[[c, b, a], [c, b, a], [c, b, a], [c, b, a], [c, b, a], [c, b, a]]
Process finished with exit code 0
這種問題比較詭異,因為它沒有複制,隻是疊代周遊了數組:
要這種修改,把值複制出來:
package com.zhang.arrangementselect;
import org.junit.jupiter.api.Test;
import org.raistlic.common.permutation.Permutation;
import java.util.*;
/**
* @description: 産生兩個不同的數字
* @author: zhangyu
* @create: 2019-09-26 14:18
*/
public class GenerateTwoNumber {
@Test
public void getPermutationFun() {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<List<String>> newList = new ArrayList<>();
for (List<String> p : Permutation.of(list)) {
System.out.println();
newList.add(new ArrayList<>(p));
}
System.out.println(newList);
}
}
運作結果:
[a, b, c]
[a, c, b]
[b, a, c]
[b, c, a]
[c, a, b]
[c, b, a]
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]]
把那個對象複制出現就好了,不會出現一直疊代的問題。是以就解決了排列的問題。