`
雷博弈
  • 浏览: 16916 次
  • 性别: Icon_minigender_1
  • 来自: 四川
文章分类
社区版块
存档分类
最新评论

数组的排序和打印

阅读更多
今天一个朋友打印一个三位数组,我看了后,写了一个通用的。贴出来,也不至于Blog这么空荡。
Integer[] array = new Integer[] { 1, 2 ,3}以此数组为例。
    
Set set = new HashSet();//用来装排序后的下标
//计算数组有多少种排序方式。
int count = 1;
for (int cou = 2; cou <= array.length; cou++) {
count = count * cou;
}

while (true) {
// 用来储存数组下标
List list = new ArrayList();
for (int j = 0; j < array.length; j++) {
int s = new Random().nextInt(array.length);
list.add(s);
}
// 用来过虑重复的下标,如 1,1,0
Set indexSet = new HashSet();
for (Object object4 : list) {
indexSet.add(object4);
}
// 过虑后的下标,(是合法的加入set集合)
if (indexSet.size() == array.length) {
set.add(list);
}
// 看是不是达到了数据的排列方式的总数
if (set.size() == count) {
break;
}
}
// 输出
for (Object object : set) {
// 判断是不是List
if (object instanceof List) {
// 强转(里面装的是数字下标)
List curList = (List) object;
// 用来装排列后的集合
List<List> allList = new ArrayList<List>();
// 用来装排列后的数组
List newList = new ArrayList();
for (Object object3 : curList) {
// 添加到新的集合
newList.add(array[new Integer(object3.toString())]);
// 如果他的长度和数组的长度相同,说明是一个数组
if (newList.size() == array.length) {
// 添加到总的集合
allList.add(newList);
}
}
for (List list : allList) {
System.out.println(list.toString());
}
}
}


------打印结果------
[3, 2, 1]
[1, 3, 2]
[2, 3, 1]
[2, 1, 3]
[3, 1, 2]
[1, 2, 3]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics