当前位置:网站首页>ByteDance Written Exam 2020 (Douyin E-commerce)

ByteDance Written Exam 2020 (Douyin E-commerce)

2022-08-09 06:33:00 The strongest disciple in history

Title: Write a program that randomly assigns weights.

I thought about it when I got this question. Fortunately, I read Ribbon's weighting algorithm before.The core idea is to add up all the weight values, do random value calculation, and finally determine the position of the random value in the total weight value, so as to determine the data.

import java.util.ArrayList;import java.util.List;public class Test12 {//weight algorithmpublic Weight getWeight(List list){int totalWeight = 0;for(Weight weight:list){totalWeight += weight.getValue();}double random = Math.random();Integer weightValue = new Double(Math.ceil(random*totalWeight)).intValue();totalWeight = 0;for(Weight weight:list){totalWeight += weight.getValue();if(weightValue - totalWeight<=0){return weight;}}return null;}public static void main(String[] args) {Weight weight = new Weight(1,"A");Weight weight2 = new Weight(2,"B");Weight weight3 = new Weight(3,"C");List list = new ArrayList<>();list.add(weight);list.add(weight2);list.add(weight3);Test12 test12 = new Test12();Weight returnWeight = test12.getWeight(list);System.out.println(returnWeight);}}class Weight{private Integer value;private String name;public Weight(Integer value, String name){this.value = value;this.name = name;}public Integer getValue() {return value;}}

Output result:

原网站

版权声明
本文为[The strongest disciple in history]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090629203702.html