Provide a red envelope algorithm, readily written, there are many areas to be optimized, but the efficiency is higher,
Test efficiency: 1 million times, 20 red envelopes need about 1.3 seconds
1 million times, 100 red envelopes need about 6.3 seconds
Code implementation:
Import Java.util.arraylist;import java.util.list;import java.util.random;/** * Calculate RED envelope allocation * * @author LENOVO * */public final Class Redpacketutil {public static void main (string[] args) {Long start = System.currenttimemillis (); list<long> list = Null;int num = 1000000;int count = 100;for (int i = 0;i<num;i++) {list = Redpacketutil.generat Eredpacket (10000L, Count, 30L);} System.out.println ("Last Red Packet data:" + list); Long total = 0l;for (long item:list) {total + = Item;} System.out.println ("Number of requests for red envelopes:" + num); System.out.println ("Each red envelope number:" + count); SYSTEM.OUT.PRINTLN ("Total Amount:"); Long end = System.currenttimemillis (); System.out.println ("spents:" + (End-start));} /** * * @param total red Envelope amount * @param count of Red packets * @param low The minimum value of a single (one number between 1-99) * @return */public static list< Long> generateredpacket (Long total,int count,long low) {list<long> rtList = new arraylist<> (); Long avg = total/count;if (avg <= 0) {throw new RuntimeException ("minimum value cannot be less than or equal to 0");} Long remainDer = Total%count; Long Lowvalue = Avg*low/100;lowvalue = Lowvalue = = 0?1:lowvalue; Long othervalue = avg-lowvalue;for (int i=0;i<count;i++) {rtlist.add (lowvalue);} Random random = new random (), if (Othervalue > 0) {for (int i=0;i<count;i++) {Long Driftamount = Othervalue * Ran Dom.nextint (/10;int addindex = Random.nextint (count); int reduceindex = Random.nextint (count); Rtlist.set (AddIndex, Rtlist.get (Addindex) + driftamount) Rtlist.set (Reduceindex, Rtlist.get (reduceindex) + Othervalue-driftamount);}} int addindex = Random.nextint (count); Rtlist.set (Addindex, Rtlist.get (addindex) + remainder); return rtList;}}
Millions, 20 of red envelopes. 1.3 seconds
100 Red envelopes for 6.3 seconds
Millions of 10 red envelopes. 0.7 seconds
A high efficiency red envelope algorithm