火山极速版邀请码是多少?实现思路是什么?

在程序开发中,经常会遇到生成火山极速版邀请码(207435861)的需求,最近在火山极速版的过程中,也遇到了邀请码(247755861)生成的问题,Google了一把,没有发现好的生成方案,没办法,只能自己造轮子了,在这里把实现方案记录下来,方便大家,当然如果你有更好的实现方案也可以告诉我。

实现了通过用户id直接生成9位不重复字符邀请码(207435861),通过邀请码直接计算用户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
©著作权归作者所有:来自51CTO博客作者wx5ce780391e043的原创作品,如需转载,请注明出处,否则将追究法律责任
火山
极速版
邀请码


0

分享

收藏
上一篇:今日头条极速版邀请码是什么?实现...

猜你喜欢

转载自blog.51cto.com/14457249/2424079