JAVA實現紅包分發的示例代碼

大體思路

如果發總金額為 m的 n 個紅包,先用一個長度為 n的臨時數組 a 存放 n個隨機雙精度小數

,然後用  sum表示數組 a 的和,每個紅包的金額

代碼

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 紅包分發內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet! 

推薦閱讀:

    None Found