Przypuśćmy, że chcę stworzyć grę. Na początku gry gracz wybierze potwora.Jak napisać algorytm prawdopodobieństwa, który można łatwo utrzymać?
Łatwo wybrać potwora w odpowiedni sposób.
// 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];
}
i podnosi potwora niesprawiedliwie.
// 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();
}
}
Problem polega na tym, że po dodaniu nowego potwora do gry, muszę edytować if-else. Lub zmieniam szansę na wygraną GoldMonster na 0,2, muszę zmienić wszystkie 0.1 na 0.2 . Jest brzydki i niełatwo go utrzymać.
// 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();
}
}
Jak to algorytm prawdopodobieństwo może być refactored tak że kody mogą być utrzymywane łatwo, gdy nowy potwór dodaje a szanse na wygraną są dostosowane potworów?
Wybierz char z losowej pozycji ciągu 'GSSBBBBBBB'. Taki ciąg jest łatwy do zmiany. –