java后台根据权重返回抽奖结果
直接代码:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class WeightedAllocator {
public static Prize allocateByWeight(List<Prize> items) {
if (items.isEmpty()) {
return null;
}
int totalWeight = 0;
for (Prize item : items) {
totalWeight += item.getPrizeWeight();
}
int randomValue = new Random().nextInt(totalWeight);
int currentSum = 0;
for (Prize item : items) {
currentSum += item.getPrizeWeight();
if (randomValue < currentSum) {
return item;
}
}
return items.get(items.size() - 1); // Should never happen
}
public static void main(String[] args) {
Prize prize = new Prize();
prize.setPrizeName("A");
prize.setPrizeWeight(1);
Prize prize2 = new Prize();
prize2.setPrizeName("B");
prize2.setPrizeWeight(7000);
Prize prize3 = new Prize();
prize3.setPrizeName("C");
prize3.setPrizeWeight(2999);
List<WeightedItem<Prize>> items = new ArrayList<>();
items.add(new WeightedItem<>(prize, prize.getPrizeWeight())); // 30% chance of being selected
items.add(new WeightedItem<>(prize2, prize2.getPrizeWeight()));
items.add(new WeightedItem<>(prize3, prize3.getPrizeWeight()));
int[] counts = new int[3];
for (int i = 0; i < 10000; i++) {
Prize result = allocateByWeight(items);
switch (result.getPrizeName()) {
case "A": counts[0]++; break;
case "B": counts[1]++; break;
case "C": counts[2]++; break;
}
}
// Print the results
for (int i = 0; i < counts.length; i++) {
System.out.println("Item " + (char)('A' + i) + ": " + counts[i] + "次");
System.out.println("Item " + (char)('A' + i) + ": " + (counts[i] * 100 / 10000) + "%");
}
}
}