import java.util.Random;
/**
* 邀请码生成器,算法原理:<br/>
* 1) 获取id: 1127738 <br/>
* 2) 使用自定义进制转为:gpm6 <br/>
* 3) 转为字符串,并在后面加'o'字符:gpm6o <br/>
* 4)在后面随机产生若干个随机数字字符:gpm6o7 <br/>
* 转为自定义进制后就不会出现o这个字符,然后在后面加个'o',这样就能确定唯一性。最后在后面产生一些随机字符进行补全。<br/>
* @author jiayu.qiu
*/
public classShareCodeUtil {
/** 自定义进制(0,1没有加入,容易与o,l混淆) */
privatestaticfinal char[] r=newchar[]{
'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'};
/** (不能与自定义进制有重复) */
privatestaticfinal charb='o';
/** 进制长度 */
privatestaticfinal intbinLen=r.length;
/** 序列最小长度 */
privatestaticfinal ints=6;
/**
* 根据ID生成六位随机码
* @param id ID
* @return 随机码
*/
publicstaticString toSerialCode(longid) {
char[] buf=newchar[32];
intcharPos=32;
while((id / binLen) > 0) {
intind=(int)(id % binLen);
// System.out.println(num + "-->" + ind);
buf[--charPos]=r[ind];
id /= binLen;
}
buf[--charPos]=r[(int)(id % binLen)];
// System.out.println(num + "-->" + num % binLen);
String str=newString(buf, charPos, (32- charPos));
// 不够长度的自动随机补全
if(str.length() < s) {
StringBuilder sb=newStringBuilder();
sb.append(b);
Random rnd=newRandom();
for(inti=1; i < s - str.length(); i++) {
sb.append(r[rnd.nextInt(binLen)]);
}
str+=sb.toString();
}
returnstr;
}
publicstaticlong codeToId(String code) {
charchs[]=code.toCharArray();
longres=0L;
for(inti=0; i < chs.length; i++) {
intind=0;
for(intj=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;
}
// System.out.println(ind + "-->" + res);
}
returnres;
}
}
今天的文章邀请码生成器Java代码分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/66269.html