基于用户id的最优邀请码生成方案

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

实现了通过用户id直接生成6位不重复字符邀请码,通过邀请码直接计算用户id

源码下载:

https://www.haidaoshu.com/file/cicada.zip

小小自私一下偷笑,海盗鼠( https://www.haidaoshu.com) 程序员的零花钱帮手

需求如下:

邀请码由6位不重复数字字母组成
用户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个字符进行排列组合,共可生成32*31*30*29*28*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

未经允许不得转载:极速云 » 基于用户id的最优邀请码生成方案

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址