【发布时间】:2013-11-09 11:55:11
【问题描述】:
我正在创建一个程序,其中涉及一段代码,我需要在其中从单个项目(名称)列表中选择对。
初始列表来自单个ArrayList<String>,其中包含所有唯一的人名。
我的尝试如下:
//Performance is not really a focus as the lists are small (20 ~ 60 elements),
//thus I use a SecureRandom instead of a Random.
SecureRandom rnd = new SecureRandom();
//List of names
ArrayList<String> Names = new ArrayList<>();
//Names populated somewhere here..
//Make a secondary array which houses the available names...
ArrayList<String> AvailNames = new ArrayList<>();
AvailNames.addAll(Names);
LinkedHashMap<String, String> NamePair = new LinkedHashMap<>();
Iterator<String> Iter = Names.iterator();
// LOOP A
while(Iter.hasNext()){
String name = Iter.next();
int index;
/*
* LOOP B
* Find a unique pair randomly, looping if the index is the same.
* Not the most efficient way, but gets the job done...
*/
while(true){
index = rnd.nextInt(AvailNames.size());
if(!AvailNames.get(index).equals(name)){
break;
}
}
NamePair.put(name, AvailNames.remove(index));
}
当名字的数量是奇数时,我遇到了LOOP B(见上文)无限期运行的问题。
我发现问题在于,有时,当所有对都被取走时,剩下的姓氏对是非唯一的,导致 if 语句永远不会为真。
以列表为例:
- 一个
- B
- C
- D
- 电子
程序在执行期间可能会先从 A 到 D 排序,创建一个名称对,如下所示:
- A - B
- B - C
- C - D
- D - C
留下E - E 作为最后一对,不允许作为一对(因为项目/名称不是唯一)。由于配对分配是随机的,因此有时会起作用,有时会不起作用,坦率地说,这很烦人……
我确信解决方案非常简单,但由于某种原因,我似乎无法找到解决此问题的方法。任何帮助表示赞赏。
【问题讨论】:
-
这是一个有趣的问题。当 AvailNames.size 为 2 并手动配对最后两个时,也许可以通过退出循环来保证不会发生这种情况?