自己写的发红包的算法

来源:互联网 发布:smtp端口 ssl qq 编辑:程序博客网 时间:2024/04/30 05:10

package com.gz;import java.math.BigDecimal;import java.math.MathContext;import java.math.RoundingMode;import java.text.DecimalFormat;public class RandomUtil {private static RandomUtil randomUtil=new RandomUtil();public static void main(String[] args) {for(int i=0;i<=20;i++){randomUtil.generate(100.00,12);System.out.println("---------------分割线---------------------");}}/** * 测试方法 * @param money 金额数量 * @param num 分成多少份 */private void generate(Double money,Integer num){Double totleMoney=money.doubleValue();Double count=0.0,temp=0.0;for(int i=0;i<num;i++){if(i+1==num){temp=totleMoney-count;count+=temp;DecimalFormat decimalFormat=new DecimalFormat("#0.00");System.out.println(decimalFormat.format(temp));}else{temp=randomUtil.generateUtil(money, num-i);money-=temp;count+=temp;}}System.out.println("金额合计:"+count);}/** * 生成红包的主要方法 * @param money 金额数量 * @param num 分成多少份 * @return 生成的金额 */private Double generateUtil(Double money,Integer num){Double avf=formatNum(money/num);Double tmp_money=avf+Math.random()*avf;tmp_money=formatNum(tmp_money);DecimalFormat decimalFormat=new DecimalFormat("#0.00");System.out.println(decimalFormat.format(tmp_money));return tmp_money;}/** * 负责格式化金额 * @param price 金额 * @return 格式化好的金额 */private Double formatNum(Double price){Integer precision=String.valueOf(price).lastIndexOf(".")+2;MathContext context=new MathContext(precision, RoundingMode.HALF_DOWN);BigDecimal bigDecimal=new BigDecimal(price);return  bigDecimal.round(context).doubleValue();}}

刚从集团公司调到分公司来学习,发现这边的抢红包算法机制有问题,大的特别大,小的特别小,自己闲着写了一个,测试了下,发现最后一个永远是最小的,前面的随机,因为最后一个是剩余,实在没什么好的方案了,贴出来跟大家分享

有测试方法可看到每次生成的金额数

0 0