群里有人想要这么一个数组逻辑,
String[] a = {"1","1","2","3","4","4"};
去重,获取元素所有可能存在的排列,期望结果如下:
1,2,3,4,12,13,14,23,24,123,124,1234,234,34
考虑构建一个新的队列容器,方便后面对数组做各种操作
import java.util.*;
public class PermutationQueue<E> extends ArrayDeque<E> {
public PermutationQueue(Collection<? extends E> c) {
super(c);
}
public static void main(String[] args) {
String[] a = {"1","1","2","3","4","4"};
Set<String> b = new HashSet<String>(Arrays.asList(a));
// Integer[] a = {1,1,2,3,4,4};
// Set<Integer> b = new HashSet<Integer>(Arrays.asList(a));
// 去重数据放入队列中进行排列
PermutationQueue<String> permuQueue = new PermutationQueue<String>(b);
String[] fullPermutations = permuQueue.loopQueue();
for (String per : fullPermutations){
System.out.println(per);
}
}
private String[] loopQueue(ArrayDeque<E> srcQueue, Queue<StringBuffer> elementQueue, ArrayDeque<String> permutations){
// 先将元素容器中所有元素更新
StringBuffer ele = new StringBuffer(String.valueOf(srcQueue.poll()));
for (StringBuffer element : elementQueue){
element.append(ele);
}
elementQueue.add(ele);
// 再loop两个容器
for (E src : srcQueue){
for (StringBuffer element : elementQueue){
permutations.add(element + String.valueOf(src));
}
}
if (srcQueue.size() > 1) loopQueue(srcQueue, elementQueue, permutations);
return permutations.toArray(new String[]{});
}
public String[] loopQueue(){
ArrayDeque<String> elements = new ArrayDeque<String>();
for (E ele : this.clone()){
elements.add(String.valueOf(ele));
}
return this.loopQueue(this.clone() , new ArrayDeque<StringBuffer>() , elements);
}