import lombok.Getter; | |
public class Chance { | |
@Getter | |
private Object object; | |
@Getter | |
private int chance; | |
public Chance(Object obj, int chance) { | |
this.object = obj; | |
this.chance = chance; | |
} | |
} |
import java.util.List; | |
import java.util.Random; | |
public class ChanceAPI { | |
private Chance[] chances = null; | |
public static ChanceAPI init() { | |
return new ChanceAPI(); | |
} | |
public void add(Chance[] chance) { | |
this.chances = chance; | |
} | |
public Object generateRandom() { | |
int total = 0; | |
for(Chance chance : chances) { | |
total += chance.getChance(); | |
} | |
int rand = new Random().nextInt(total); | |
int sum = 0; | |
int i = 0; | |
while(sum < rand) { | |
sum += chances[i++].getChance(); | |
} | |
return chances[Math.max(0, i-1)].getObject(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment