JAVA作业——红包分发

JAVA作业——红包分发

JAVA作业——红包分发

大体思路

如果发总金额为 m m m n n n 个红包,先用一个长度为 n n n 的临时数组 a a a 存放 n n n 个随机双精度小数 ( 0 ≤ a i < 1 ) (0 \leq a_i<1) (0ai<1) ,然后用 s u m sum sum 表示数组 a a a 的和,每个红包的金额 b i = a i s u m ⋅ m b_i =\frac{a_i}{sum} \cdot m bi=sumaim

代码

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);
    }
}
  • 19
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值