package cc.mrbird.febs.dapp.utils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.RandomUtil; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author wzy * @date 2022-07-14 **/ @Slf4j public class BoxUtil { public static volatile List boxList = Collections.synchronizedList(new ArrayList<>()); public synchronized static Box openBox() { if (CollUtil.isEmpty(boxList)) { Box box1 = new Box(1, 6); Box box2 = new Box(2, 1); Box box3 = new Box(3, 1); Box box4 = new Box(4, 1); Box box5 = new Box(5, 1); boxList.add(box1); boxList.add(box2); boxList.add(box3); boxList.add(box4); boxList.add(box5); } int min = 1; int minIndex = 1; int max = 1; for (int i = 0; i < boxList.size(); i++) { Box box = boxList.get(i); if (i != 0) { minIndex += boxList.get(i - 1).getCount(); } max += box.getCount(); box.setMin(minIndex); box.setMax(max); } int i = RandomUtil.randomInt(min, max); Box result = new Box(); for (Box box : boxList) { if (box.getMin() <= i && box.getMax() > i) { result = box; int count = box.getCount(); count--; box.setCount(count); if (count == 0) { boxList.remove(box); } break; } } return result; } public static class Box { private int index; private int count; public Box() {} public Box(int index, int count) { this.index = index; this.count = count; } private int min; private int max; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getMin() { return min; } public void setMin(int min) { this.min = min; } public int getMax() { return max; } public void setMax(int max) { this.max = max; } } }