Skip to content

Instantly share code, notes, and snippets.

@Ragnok123
Created January 10, 2021 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ragnok123/e7102ecf6b37abfe038c59c67cc2c091 to your computer and use it in GitHub Desktop.
Save Ragnok123/e7102ecf6b37abfe038c59c67cc2c091 to your computer and use it in GitHub Desktop.
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