Java實現微信紅包隨機金額算法
class RandSplitNumUtils {
private static final Random random = new Random();
/**
* 根據總數分割個數及限定區間進行數據隨機處理
* 數列浮動閥值爲0.95
* @param total - 被分割的總數
* @param splitNum - 分割的個數
* @param min - 單個數字下限
* @param max - 單個數字上線
* @return - 返回符合要求的數字列表
*/
public static List<Integer> genRandList(int total, int splitNum, int min, int max) {
return genRandList(total, splitNum, min, max, 0.95f);
}
/**
* 根據總數分割個數及限定區間進行數據隨機處理
* @param total - 被分割的總數
* @param splitNum - 分割的個數
* @param min - 單個數字下限
* @param max - 單個數字上線
* @param thresh - 數列浮動閥值[0.0, 1.0]
* @return
*/
public static List<Integer> genRandList(int total, int splitNum, int min, int max, float thresh) {
assert total >= splitNum * min && total <= splitNum * max;
assert thresh >= 0.0f && thresh <= 1.0f;
// 平均分配
int average = total / splitNum;
List<Integer> list = new ArrayList<>(splitNum);
int rest = total - average * splitNum;
for (int i = 0; i < splitNum; i++) {
if (i < rest) {
list.add(average + 1);
} else {
list.add(average);
}
}
// 如果浮動閥值爲0則不進行數據隨機處理
if (thresh == 0) {
return list;
}
// 根據閥值進行數據隨機處理
for (int i = 0; i < splitNum - 1; i++) {
int nextIndex = i + 1;
int rangeThis = Math.min(list.get(i) - min, max - list.get(i));
int rangeNext = Math.min(list.get(nextIndex) - min, max - list.get(nextIndex));
int rangeFinal = (int) Math.ceil(thresh * (Math.min(rangeThis, rangeNext) + 1));
int randOfRange = random.nextInt(rangeFinal);
int randRom = list.get(i) > list.get(nextIndex) ? -1 : 1;
list.set(i, list.get(i) + randRom * randOfRange);
list.set(nextIndex, list.get(nextIndex) + randRom * randOfRange * -1);
}
return list;
}
public static void main(String[] args) {
System.out.println(genRandList(10000, 300, 1, 200));
}
}
// 共10000隨機分成300份,最小值爲1,最大值爲200。
genRandList(10000, 300, 1, 200, 0.95f)
genRandList(10000, 300, 1, 200, 0.5f)