使用id生成6位數(字母加數字),親測不會重複
阿新 • • 發佈:2021-01-31
使用id生成6位數(字母加數字),親測不會重複
package cn.wkgb.common.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
- 根據id生成6位數
- @author Administrator
/
public class ShareCodeUtil {
/*
* 邀請碼生成器,演算法原理:
* 1) 獲取id: 1111111
* 2) 使用自定義進位制轉為:gpm6
* 3) 轉為字串,並在後面加’O’字元:gpm6o
* 4)在後面隨機產生若干個隨機數字字元:gpm6o7
*/
/** 自定義進位制(0,1沒有加入,容易與o,l混淆) */ private static final char[] r=new char[]{'Q', 'W', 'E', '8', 'A', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P', '5', 'I', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'V', 'Y', 'l', 'T', 'N', '6', 'B', 'G', 'H'}; /** (不能與自定義進位制有重複) */ private static final char b='O'; /** 進位制長度 */ private static final int binLen=r.length; /** 序列最小長度 */ private static final int s=6; /** * 根據ID生成六位隨機碼 * @param id ID * @return 隨機碼 */ public static String toSerialCode(long id) { char[] buf=new char[32]; int charPos=32; while((id / binLen) > 0) { int ind=(int)(id % binLen); buf[--charPos]=r[ind]; id /= binLen; } buf[--charPos]=r[(int)(id % binLen)]; String str=new String(buf, charPos, (32 - charPos)); // 不夠長度的自動隨機補全 if(str.length() < s) { StringBuilder sb=new StringBuilder(); sb.append(b); Random rnd=new Random(); for(int i=1; i < s - str.length(); i++) { sb.append(r[rnd.nextInt(binLen)]); } str+=sb.toString(); } return str; } public static long codeToId(String code) { char chs[]=code.toCharArray(); long res=0L; for(int i=0; i < chs.length; i++) { int ind=0; for(int j=0; j < binLen; j++) { if(chs[i] == r[j]) { ind=j; break; } } if(chs[i] == b) { break; } if(i > 0) { res=res * binLen + ind; } else { res=ind; } } return res; } public static void main(String[] args) { Map<String, Object> map = new HashMap<String, Object>(); int a=0; for (int i = 0; i < 10000000; i++) { String s = toSerialCode(i); if (map.get(s)!=null) { a++; }else { map.put(s, "2"); } } System.out.println(a); }
}