Skip to content

Instantly share code, notes, and snippets.

@Ribesg
Last active January 3, 2016 12:29
Show Gist options
  • Save Ribesg/8463592 to your computer and use it in GitHub Desktop.
Save Ribesg/8463592 to your computer and use it in GitHub Desktop.
// INPUT
final Map<ItemStack, Double> myItemsWithWeight; // Initialized somewhere before that
// Data
final List<ItemStack> myItems = new ArrayList<>(myItemsWithWeight.size());
final double[] risingWeights = new double[myItemsWithWeight.size()];
// Compute total weight
double total = 0;
for (final double d : myItemsWithWeight.values()) {
total += d;
}
// Transform input into useful data
int i = 0;
double previous = 0;
for (final Entry<ItemStack, Double> e : myItemsWithWeight.entrySet()) {
myItems.set(i, e.getKey());
previous += e.getValue() / total;
risingWeights[i] = previous;
i++;
}
// Now use our wonderful data
final float f = new Random().nextFloat();
for (i = 0; i < risingWeights.length; i++) {
if (f < risingWeights[i]) {
return myItems.get(i); // Enjoy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment