距离上一次写博已过了好久。。也是有点偷懒了
今天带来不久前对优惠券编码的随机生成代码分享。
需求:给指定会员发放指定几种类型的优惠券,每类发一种
参数:会员ID、优惠券类型ID集合
生成规则:
系统时间随机生成数字- >5位
+会员ID(左填充0) - >5位
+类型ID - >1位
+随机5位之母插入以上生成的11位的不同位置
package com.**.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; public class CouponCodeAutoGenerate { public static CouponCodeAutoGenerate generate =null; private final static String NUM_CHAR = "0123456789"; private static int charLen = NUM_CHAR.length(); private CouponCodeAutoGenerate(){ } public static CouponCodeAutoGenerate getInstance(){ if(generate ==null){ generate =new CouponCodeAutoGenerate(); } return generate; } public Map<Long,String> autoGenerateCouponCode(Long memberId,List<Long> idList){ Map<Long,String> map =new HashMap<Long, String>(); StringBuilder sb =null; StringBuilder sbr =null; int[] intRet = null; int insertIndex =0; for(Long id :idList){ sb=new StringBuilder(); //系统时间 5位 sb.append(getRandomByCurrentTime(5)); //memberId 5位左填充0 sb.append(String.format("%05d",memberId)); //类型 1位 sb.append(id); // 5个随机字母 sbr=new StringBuilder(getRandChar(5)); intRet =getRetIndex(5,sb.length()+1); for(int i=0;i<sbr.length();i++){ insertIndex =intRet[i]+i; sb.insert(insertIndex, sbr.charAt(i)); } map.put(id, sb.toString()); } return map; } public String getRandChar(int s){ String val =""; for(int i=0 ;i <s ;i++){ Random random = new Random(); int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母 val += (char) (choice + random.nextInt(26)); } return val ; } public String getRandomByCurrentTime(int randomNumberDigit) { long seed = System.currentTimeMillis();// 获得系统时间,作为生成随机数的种子 StringBuffer sb = new StringBuffer();// 装载生成的随机数 Random random = new Random(seed);// 调用种子生成随机数 for (int i = 0; i < randomNumberDigit; i++) { sb.append(NUM_CHAR.charAt(Math.abs(random.nextInt())% charLen)); } return sb.toString(); } //替换位置 //从0-t中取s个不同数字 public int[] getRetIndex(int s,int t) { // TODO Auto-generated method stub int[] intRet = new int[s]; int intRd = 0; //存放随机数 int count = 0; //记录生成的随机数个数 int flag = 0; //是否已经生成过标志 while(count<s){ Random rdm = new Random(); intRd = Math.abs(rdm.nextInt())% t; for(int i=0;i<count;i++){ if(intRet[i]==intRd){ flag = 1; break; }else{ flag = 0; } } if(flag==0){ intRet[count] = intRd; count++; } } return intRet; } public static void main(String[] args) { List<Long> typeList =new ArrayList<Long>(); typeList.add(1L); typeList.add(2L); typeList.add(3L); Map<Long,String> code =CouponCodeAutoGenerate.getInstance().autoGenerateCouponCode(23l, typeList); Set<Map.Entry<Long,String>> it =code.entrySet(); for (Map.Entry<Long,String> entry : it) { System.out.println(entry.getKey()+"---"+entry.getValue()); } } }
时间: 2024-09-07 19:23:56