All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.jackpanz.spring.util.RandomWeightUtil Maven / Gradle / Ivy

The newest version!
package com.github.jackpanz.spring.util;

/**
 * Created by Administrator on 2016/7/25.
 */
public class RandomWeightUtil {

    /**
     * 按照權重并隨機抽取
     * **/
    public static int percentageRandom(int[] elements,int[] weights) {
        int random = -1;
        try{
            double sumWeight = 0,randomNumber = Math.random(),d1 = 0,d2 = 0;
            //计算总权重
            for(Integer w : weights){
                sumWeight += w;
            }

            for(int i=0;i= d1 && randomNumber <= d2){

                    random = elements[i];
                    break;
                }
            }
        }catch(Exception e){
            throw new RuntimeException(e.getMessage());
        }
        return random;
    }

    public static void main(String[] args) {
        int[] ids = {1,2,3,4,5};
        int[] weights = {1,1,0,0,9};
        for(int i=0;i<20;i++)
        {
            System.out.println(percentageRandom(ids,weights));
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy