Java micro-letter random red Envelope algorithm code example _java

Source: Internet
Author: User

One night a few days ago, a sudden thought of a micro-letter red envelope should have a random algorithm, try to write on their own, do not know right, looked at the internet, as if so far the official did not give an exact algorithm, had to shortcoming here, first posted code:

 public static double [] Getmoney (double, int num) {Random r = new Random ();
    
    DecimalFormat format = new DecimalFormat (". #");
    Double middle = double.parsedouble (Format.format (money/num));
    Double [] Dou = new Double[num];
    Double Redmoney = 0;
    Double Nextmoney = money;
    Double sum = 0;
    int index = 0;
      for (int i=num;i>0;i--) {if (i = = 1) {Dou[index] = Nextmoney;
          }else{while (true) {String str = Format.format (r.nextdouble () *nextmoney);
          Redmoney = double.parsedouble (str);
          if (redmoney>0 && Redmoney < middle) {break;
        } Nextmoney = Double.parsedouble (Format.format (Nextmoney-redmoney));
        sum = sum + Redmoney;
        Dou[index] = Redmoney;
        Middle = double.parsedouble (Format.format (nextmoney/(i-1)));
      index++;
  } return dou; }

One of the basic ideas here is this: first calculate the average value of red envelopes, and then through a random red packets less than the average number of red envelopes, when the red envelopes, the total amount of red envelopes need to be correspondingly reduced, and recalculate the average: The new total amount (the original total red envelope number-1), until the last red envelope, Cram all the remaining money into it.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.