一个效率比较高红包算法
提供一个红包算法,随手写的,还有很多需要优化的地方,但是效率比较高,
测试效率:一百万次 ,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;
}
}
百万次 ,20 个的 红包 。 1.3 秒

百万次 100 个的 红包 6.3 秒

百万次 10 个 红包。0.7 秒

能耍的时候就一定要耍,不能耍的时候一定要学。
--天道酬勤,贵在坚持posted on 2018-07-13 15:36 zhangyukun 阅读(284) 评论(0) 收藏 举报
浙公网安备 33010602011771号