Java 基于权重按比例分配算法

public class WeightRandomStrategy<K, V extends Number> {
    private TreeMap<Double, K> weightMap = new TreeMap<>();

    public WeightRandomStrategy(List<Pair<K, V>> list) {
        for (Pair<K, V> pair : list) {
            double lastWeight = this.weightMap.size() == 0 ? 0 : this.weightMap.lastKey();
            this.weightMap.put(pair.getValue().doubleValue() + lastWeight, pair.getKey());
        }
    }

    public K random() {
        double randomWeight = this.weightMap.lastKey() * Math.random();
        SortedMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false);
        return this.weightMap.get(tailMap.firstKey());
    }
}
List<Pair<String, Integer>> list = new ArrayList<>();
list.add(new ImmutablePair<>("TR", 90));
list.add(new ImmutablePair<>("TX", 10));
WeightRandomStrategy<String, Integer> strategy = new WeightRandomStrategy<>(list);
int a = 0, b = 0;
for (int i = 0; i < 10000; i++) {
    switch (strategy.random()) {
        case "TR":
            a++;
            break;
        case "TX":
            b++;
            break;
        default:
            break;
    }
}
System.out.println("a=" + a + ", b=" + b);
System.out.println("a+b=" + (a + b));

---------------------------------------------------output
a=8993, b=1007
a+b=10000

修改myeclipse默认字体风格

  虽说等宽字体是最好的显示代码字体,不过依旧习惯xp下面的tahoma。不喜欢斜体,看着别扭。myeclipse选项实在是太多,找起来麻烦,特在此记录一些常用的。

  1. 编辑器全局字体(搜索fonts)
  2. General - Appearance - Colors and Fonts
    展开Basic找到Text Font,双击即可修改。
  3. 修改html,xml,css等属性值为斜体(搜索styles)
  4. MyEclipse - File and Editors下面的所有代码风格依个人喜好改。
    CSS Styles - Property Value 右侧取消选择Italic(斜体)
    HTML Styles - Attribute Values 同样取消Italic
  5. 代码自动提示(搜索assist)
  6. 找到Java - Editor - Content Assist 右边有auto activation triggers for java可以将a到z全部加入。不过一般加入".@"就够用了。