火山極速版邀請碼是什麼?生成方案

在程序開發中,經常會遇到生成火山極速版邀請碼(247755861)的需求,最近在火山極速版的過程中,也遇到了邀請碼(247755861)生成的問題,Google了一把,沒有發現好的生成方案,沒辦法,只能自己造輪子了,在這裏把實現方案記錄下來,方便大家,當然如果你有更好的實現方案也可以告訴我。

   實現了通過用戶id直接生成9位不重複字符邀請碼(247755861),通過邀請碼直接計算用戶id
需求如下:

邀請碼由9位不重複數字字母組成
用戶id和邀請碼可以相互轉化
實現思路大概是
//驗證碼字符列表
private static final char STUFFS[] = {
'A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','P','Q',
'R','S','T','U','V','W','X','Y',
'1','2','3','4','5','6','7','8'};
32個字母數字中取6個字符進行排列組合,共可生成3231302928*27=652458240個邀請碼,我們只需要實現652458240個數字和其一一對應即可,下面是編碼的過程,解碼過程逆向就可以了。

1、將數字拆分成組合序號和排列序號

 1:ABCDEF  2:ABCDEG 3:ABCDEH 以此類推

//PERMUTATION = 6!
//MAX_COMBINATION = 32!/(32-6)!/6!
public static String encode(int val) {
int com = val / PERMUTATION;
if(com >= MAX_COMBINATION) {
throw new RuntimeException("id can't be greater than 652458239");
}
int per = val % PERMUTATION;
char[] chars = combination(com);
chars = permutation(chars,per);
return new String(chars);
}

2、通過組合序號獲取字符組合
private static char[] combination(int com){
char[] chars = new char[LEN];
int start = 0;
int index = 0;
while (index < LEN) {
for(int s = start; s < STUFFS.length; ++s ) {
int c = combination(STUFFS.length - s - 1, LEN - index - 1);
if(com >= c) {
com -= c;
continue;
}
chars[index++] = STUFFS[s];
start = s + 1;
break;
}
}
return chars;
}
3、通過排列序號對字符進行排序
private static char[] permutation(char[] chars,int per){
char[] tmpchars = new char[chars.length];
System.arraycopy(chars, 0, tmpchars, 0, chars.length);
int[] offset = new int[chars.length];
int step = chars.length;
for(int i = chars.length -1;i >= 0;--i) {
offset[i] = per % step;
per /= step;
step --;
}
for(int i = 0; i < chars.length;++i) {
if(offset[i] == 0)
continue;
char tmp = tmpchars[i];
tmpchars[i] = tmpchars[i - offset[i]];
tmpchars[i - offset[i]] = tmp;
}
return tmpchars;
}
3、測試用例
Random random = new Random();
for(int i = 0; i < 100000;++i) {
int id = random.nextInt(652458240);
String code = encode(id);
int nid = decode(code);
System.out.println( id + " -> " + code + " -> " + nid);
}
結果如下:

521926735 -> 1SVR5G -> 521926735
281504940 -> CRKISU -> 281504940
174311333 -> WSQMFB -> 174311333
198381828 -> V3IBN6 -> 198381828
450572266 -> T1VHFJ -> 450572266
229325485 -> LJGC4D -> 229325485
132906750 -> CIVBW4 -> 132906750
388658714 -> FPX2EM -> 388658714
184756314 -> 2BGPT8 -> 184756314

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章