阿里研发工程师编程题——红包算法

一、题目

红包算法,给定一个红包总金额和分红包的人数,输出每个人随机抢到的红包数量。
要求:

  1. 每个人都要抢到红包,并且金额随机
  2. 每个人抢到的金额数不小于1
  3. 每个人抢到的金额数不超过总金额的30%
    例如总金额100,人数10,输出【19 20 15 1 25 14 2 2 1 1】

输入例子1:

100 10

输出例子1:

【19 20 15 1 25 14 2 2 1 1】

二、代码实现

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class GrabRedEnvelope {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Double> list = null;
        double money = 0;
        Random random = new Random();
        while (sc.hasNext()) {
            double totalMoney = sc.nextDouble();
            int count = sc.nextInt();
            list = new ArrayList<>(count);
            while (count > 1) {
                double max = totalMoney * 0.3;
                double r = random.nextDouble();
                money = r * max;
                if (money < 1) {
                    money = 1;
                } else {
                    money = Math.floor(money * 100) / 100;
                }
                list.add(money);
                count--;
                totalMoney -= money;
            }
            list.add(Math.floor(totalMoney * 100) / 100);
            System.out.println(list);
        }
        sc.close();
    }
}
发布了386 篇原创文章 · 获赞 313 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/riemann_/article/details/104366502