给定一个权重数组,实现一个带权重的路由策略

时间:2020-07-22 02:14:54   收藏:0   阅读:120

说明:服务的索引就是权重数组的下标

import java.util.*;

public class Client {

    public static void main(String[] args) {
        int[] arr = {3,4,5,6,7};

        List<Weight> weights = new ArrayList<>();
        int index = 0;
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            Weight weight = new Weight();
            weight.setStart(index);
            weight.setEnd(index + arr[i]);
            weight.setServer(i);
            index += arr[i];
            weights.add(weight);
            sum += arr[i];
        }
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int round = random.nextInt(sum);

            for (Weight weight : weights) {
                if(round >= weight.getStart() && round < weight.getEnd()){
                    System.out.println("round:"+round+",server:"+weight.getServer()+", start:"+weight.getStart()+",end:"+weight.getEnd());
                }
            }
        }


    }

}

 

public class Weight {
    private int start;
    private int end;
    private int server;

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!