标签:one span -- his rgs 指点 util 算法 java
微信抢红包算法:
package test;
import java.util.Random;
import java.util.Scanner;
public class WeXinRedPakage {
public static void main(String[] args) {
RedPackage redPackage = new RedPackage();
Scanner scanner = new Scanner(System.in);
//下面两步应该做校验
redPackage.setRemainSize(5);//scanner.nextInt()scanner.nextInt()
redPackage.setRemainMoney(6);
double money = 0;
scanner.close();
for (int i = 0; i < 6; i++) {//假设6个人抢
money = redPackage.getRandomMoney();
System.out.println(money);
}
}
}
class RedPackage{
private double remainSize;
private double remainMoney;
public double getRemainSize() {
return remainSize;
}
public void setRemainSize(int remainSize) {
this.remainSize = remainSize;
}
public double getRemainMoney() {
return remainMoney;
}
public void setRemainMoney(int remainMoney) {
this.remainMoney = remainMoney;
}
public double getRandomMoney() {
// remainSize 剩余的红包数量
// remainMoney 剩余的钱
if (this.getRemainSize()<1) {
System.out.println("_______");
return 0;
}
if (this.remainSize == 1) {
remainSize--;
double money = Math.round(remainMoney * 100);
return (money / 100);
}
Random r = new Random();
double min = 0.01; //
double max = remainMoney / remainSize * 2;
double money = r.nextDouble() * max;
money = money > min ? money : min;
money = Math.floor(money * 100) ;
money = money/100;
remainSize--;
remainMoney -= money;
System.out.println("-------------");
return money;
}
}
顺便讲一下指定概率算法思路:
1.按概率生成所有可能的结果放入容器
2.使用一个随机数(在指定抽奖次数范围)去访问这个容器, 获得并移除容器这个值并返回
3.抽奖一次操作一次,一直到到次数用完为止,这时候容器为零
此算法还不完善,欢迎指点。
微信抢红包算法
标签:one span -- his rgs 指点 util 算法 java
原文地址:https://www.cnblogs.com/hirampeng/p/9736034.html