package netty; import com.google.common.collect.ImmutableList; import lombok.SneakyThrows; import java.util.List; import java.util.Objects; import java.util.Random; /** * Test * * @author xfyou */ public class Test { @SneakyThrows public static void main(String[] args) { List<Integer> weightList = ImmutableList.of(0, 0, 0, 0); boolean allHaveTheSameWeight = isSameWeight(weightList); if (!allHaveTheSameWeight) { selectOneByWeight(weightList); } else { selectOneRandom(weightList); } } /** * 若是全部的權重都是同樣的,則隨機選擇一個 */ private static void selectOneRandom(List<Integer> weightList) { System.out.println("selecded list index:" + new Random().nextInt(weightList.size())); } /** * 若是全部的權重不同,則優化選擇權重高的 */ private static void selectOneByWeight(List<Integer> weightList) { int offset = new Random().nextInt(weightList.stream().mapToInt(i -> i).sum()); for (int i = 0, len = weightList.size(); i < len; i++) { offset -= weightList.get(i); if (offset < 0) { System.out.println("selected weight:" + weightList.get(i) + ", selected index:" + i); break; } } } /** * 判斷全部的權重是否同樣 */ private static boolean isSameWeight(List weightList) { boolean allHaveTheSameWeight = true; for (int i = 0, len = weightList.size(); i < len; i++) { if (i > 0) { if (!Objects.equals(weightList.get(i), weightList.get(i - 1))) { allHaveTheSameWeight = false; break; } } } return allHaveTheSameWeight; } }