大体思路
如果发总金额为 m的 n 个红包,先用一个长度为 n的临时数组 a 存放 n个随机双精度小数 ,然后用 sum表示数组 a 的和,每个红包的金额
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.util.Arrays; import java.util.Random; import java.math.*; import java.util.Scanner;
public class Main { public static long now_time; public static long seed; public static int [] get_red_packets( int money, int num) { Random random = new Random(seed); seed = random.nextLong(); int [] res = new int [num]; double [] temp= new double [num]; double sum = 0 ; int sum2 = 0 ; for ( int i = 0 ; i < num; i++) { temp[i] = random.nextDouble(); sum += temp[i]; } for ( int i = 0 ; i < num; i++) { res[i] = 1 + ( int )(temp[i] / sum * (money-num)); sum2 += res[i]- 1 ; } res[random.nextInt(num)]+=money-sum2-num; return res; }
public static void show( int [] red_packet){ System.out.println( "红包 : " + Arrays.toString(red_packet)); }
public static void main(String[] args) { int num, money; Scanner scanner = new Scanner(System.in); now_time = System.currentTimeMillis(); Random init_random = new Random(now_time); seed = init_random.nextLong(); System.out.println( "请输入要分发的红包数量:" ); num = scanner.nextInt(); System.out.println( "请输入要分发的红包总金额(分):" ); money = scanner.nextInt(); int a[] = get_red_packets(money,num); show(a); } } |
到此这篇关于JAVA实现红包分发的示例代码的文章就介绍到这了,更多相关JAVA 红包分发内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/Evrse/article/details/110144412