随机数加权轮询算法
java
public int select() {
int[] weights = {10, 20, 50};
int totalWeight = weights[0] + weights[1] + weights[2];
// 取随机数
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
for (int i = 0; i < weights.length; i++) {
offset -= weights[i];
if (offset < 0) {
return i;
}
}
return -1;
}
平滑加权轮询算法
java
int[] weights = {10, 20, 50}; // 节点权重
int totalWeight = weights[0] + weights[1] + weights[2]; // 总权重
int[] current = new int[]{10, 20, 50}; // 初始化当前权重
public int select() {
int maxCurrent = -1, selected = -1;
// 遍历所有节点,找到当前权重最大的节点
for (int i = 0; i < weights.length; i++) {
// 重新计算当前权重
current[i] += weights[i];
int cur = current[i];
if (cur > maxCurrent) {
maxCurrent = cur;
selected = i;
}
}
// 被选中的节点减去总权重
current[selected] -= totalWeight;
return selected;
}