java - 如何写一个容易维护的概率算法?

标签 java algorithm refactoring maintainability

假设我想创建一个游戏。在游戏开始时,玩家将选择一个怪物。

公平地挑选怪物很容易。

// get all monsters with equal chance
public Monster getMonsterFair(){
    Monster[] monsters = {new GoldMonster(), new SilverMonster(), new BronzeMonster()};
    int winIndex = random.nextInt(monsters.length);
    return monsters[winIndex];
}

并且不公平地选择怪物。

// get monsters with unequal chance
public Monster getMonsterUnFair(){
    double r = Math.random();
    // about 10% to win the gold one
    if (r < 0.1){
        return new GoldMonster();
    }
    // about 30% to winthe silver one
    else if ( r < 0.1 + 0.2){
        return new SilverMonster();
    }
    // about 70% to win the bronze one
    else {
        return new BronzeMonster();
    }   
}

问题是,当我向游戏添加新怪物时,我必须编辑 if-else。 或者我将赢得GoldMonster的机会更改为0.2,我必须将所有0.1更改为0.2 .它很丑,而且不容易维护。

// get monsters with unequal change & special monster
public Monster getMonsterSpecial(){
    double r = Math.random();
    // about 10% to win the gold one
    if (r < 0.1){
        return new GoldMonster();
    }
    // about 30% to win the silver one
    else if ( r < 0.1 + 0.2){
        return new SilverMonster();
    }
    // about 50% to win the special one
    else if ( r < 0.1 + 0.2 + 0.2){
        return new SpecialMonster();
    }
    // about 50% to win the bronze one
    else {
        return new BronzeMonster();
    }
}

如何重构这个概率算法,以便在添加新怪物和调整怪物获胜机会时易于维护代码?

最佳答案

基本上是@Egor Skriptunoff 所说的。这应该很容易扩展。您可以使用 Class<Monster> 的集合如果你不想使用 enum .

enum Monster {
    GOLD(1),
    SILVER(3),
    BRONZE(6) // pseudo probabilities

    private int weight;
    // constructor etc..
}

public Monster getMonsterSpecial() {
    List<Monster> monsters = new ArrayList<>();

    for(Monster monsterType : Monster.values()) {
        monsters.addAll(Collections.nCopies(monsterType.getWeight(), monsterType)); 
    }

    int winIndex = random.nextInt(monsters.length);
    return monsters.get(winIndex);
}

你也许可以使枚举 Monsters复数,并让它指向 Class<? extends Monster>如果你还想实例化怪物类。我只是想让这个例子更清楚。

关于java - 如何写一个容易维护的概率算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16855168/

相关文章:

java - Tomcat 7 日志文件差异

c - 基于斐波那契递归缓存

c# - 矩形内最大的空矩形

algorithm - 复杂度等级 P 的性质

c++ - 帮助在 C++ 中自动重命名

c# - 多线程应用的策略

java - 如何从 JavaBeanObject(泛型)写入文件

java - Java 中的 I/O 操作优化?

java - 避免覆盖 ArrayList 中的对象

c# - 使用泛型重构重复方法