提供一个红包算法,随手写的,还有很多需要优化的地方,但是效率比较高,

 

测试效率:一百万次 ,20 个红包的  需要 1.3 秒左右

    一百万次 ,100 个红包的  需要 6.3 秒左右

 

 

代码实现:

 

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

/**
 * 计算红包分配
 * 
 * @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.generateRedPacket(10000L, count ,  30L );
			}
			System.out.println("最后一个红包的数据:"  + list );
			Long total = 0L;
			for( long item : list ) {
				total += item;
			}
			System.out.println("请求红包次数:" + num );
			System.out.println("每次红包数:" + count );
			System.out.println("总金额:" + total );
			
			long end = System.currentTimeMillis();
			
			System.out.println( "用时:" + (end-start) );
		
	}
	

	/**
	 * 
	 * @param total 红包总金额
	 * @param count 红包数
	 * @param low 单个的最低值占平均值的比例( 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("最小值不能小于等于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 *  random.nextInt(10)/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;
	}

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.

 

 百万次 ,20 个的 红包 。 1.3 秒

一个效率比较高红包算法_System

 

  

 

 百万次 100 个的 红包 6.3 秒

 

一个效率比较高红包算法_List_02

 

 

百万次 10 个  红包。0.7 秒

一个效率比较高红包算法_List_03