我建立:
Map<String, Double> pseudoMap = new HashMap<String, Double>(elementCount);
在生成从 0 到 1 但不同于 0 和 1 的随机双精度数后:
double d = 0.0;
// generate double <> 0 or 1
while(d == 0.0 || d == 1.0){
d = rand.nextDouble();
}
我pseudoMap
用密钥和后缀填充了我并添加了随机数:
pseudoMap.put(unitName + "_" + i, (double)(unitMap.get(unitName) + d));
我有:
{B_15=3.1016031962291204, B_14=3.4563893967442123, B_16=3.11280085831218,
B_12=3.2976658355169466, C_8=2.6491871264729765, D_6=2.223351148643601,
B_13=3.577597012082142, C_9=2.541821826106959, D_5=2.4389896004212637,
D_4=2.2044652083865226, D_8=2.7914089043360315, D_7=2.2760755825849546,
A_1=1.6863051487791398, A_0=1.0879832608200397, C_11=2.552343819848361,
C_12=2.6759559071285404, C_10=2.7712147590013814, A_4=1.9764299942651913,
A_3=1.973038652207146, A_2=1.1844902000282258}
接下来,创建类:
public class PriorityComparator implements Comparator<String> {
Map<String, Double> base;
public PriorityComparator(Map<String, Double> base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a) <= base.get(b)) {
return -1;
} else {
return 1;
}
}
}
并按双精度值对所有 20 个单位进行排序。
要点是:由于0和1之间的随机性,它不影响独立优先级。例如,单位A
将在 1 和 1.9999999 之间流动,但永远不会跳入B
位置。
所以排序后我得到了预期:
[A, A, A, A, A, C, C, C, D, D, D, C, C, D, D, B, B, B, B, B]
这是一个完整的示例代码:
public class MonsterSort2 {
/**
* @param args
*/
public static void main(String[] args) {
int elementCount = 23;
List<String> list = new ArrayList<String>(elementCount);
Map<String, Integer> unitMap = new LinkedHashMap<String, Integer>();
unitMap.put("A", 1);
unitMap.put("C", 2);
unitMap.put("D", 2);
unitMap.put("B", 3);
Random rand = new Random();
ValueComparator bvc = new ValueComparator(unitMap);
TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bvc);
Map<String, Double> pseudoMap = new HashMap<String, Double>(elementCount);
sorted_map.putAll(unitMap);
unitMap = new LinkedHashMap<String, Integer>(sorted_map);
Iterator<String> it = unitMap.keySet().iterator();
int shift = 0;
while(it.hasNext()){
String unitName = it.next();
//prevPrior = unitList.get(unitName);
for(int i=shift; i<elementCount; i++){
//list.add(unitName);
double d = 0.0;
// generate double <> 0 or 1
while(d == 0.0 || d == 1.0){
d = rand.nextDouble();
}
pseudoMap.put(unitName + "_" + i, (double)(unitMap.get(unitName) + d));
if(i == elementCount/unitMap.size() -1 + shift){
shift = i;
break;
}
}
}//while
PriorityComparator prComp = new PriorityComparator(pseudoMap);
TreeMap<String,Double> sorted_map_total = new TreeMap<String,Double>(prComp);
sorted_map_total.putAll(pseudoMap);
list = new ArrayList<String>(elementCount);
it = sorted_map_total.keySet().iterator();
while(it.hasNext()){
String unitName = it.next();
list.add(unitName.split("_")[0]);
}//while
System.out.println(list);
}
}