生成4位不重复的邀请码
今天群里一位朋友抛出一个问题,需要用26个字母和10个数字,组成一个不重复的4位字符,来作为邀请码。既方便客户记忆,又能适应大量的用户。我就做了这个demo
package com.study.test; import java.util.Arrays; import java.util.List; public class mytest { public static void main(String[] args) { List<String> list = Arrays.asList("0", "1","2","3","4","5","6","7","8","9" , "a","b","c","d","e","f","g","h","i" , "j","k","l","m","n","o","p","q","r" , "s","t","u","v","w","x","y","z"); int begin = 0;
while (begin<10000){ String s = getString(list, begin); System.out.println("邀请码:"+s); begin++; } } private static String getString(List<String> list, int begin) { String a1; String a2; String a3; String a4; int i4 = (begin) % 36; int i3 = (begin/(36)) % 36; int i2 = (begin/(36*36)) % 36; int i1 = (begin/(36*36*36)) % 36; System.out.println(i1); System.out.println(i2); System.out.println(i3); System.out.println(i4); a1 = list.get(i1); a2 = list.get(i2); a3 = list.get(i3); a4 = list.get(i4); return a1+a2+a3+a4; } }
用Redis把begin存储起来,每次用的时候放入方法,拿到邀请码,再自增1,设置回Redis。
如此生成的邀请码最多是36*36*36*36=1679616个,一百六十万个用户,满足小型应用的需求。