n位随机非重复字符串生成算法
作者:互联网
public class Test { /** * m进制n位随机字符串生成方法 * m:大小写字母+数字生成26+26+9=61,所以可采用62进制(例子) * n:生成随机串的位数(以下以6位字符串为例) */ private static long minValue = 1000000000L; // 62^5 = 916132832,为了防止生成的短码太规律,设置初始值从1000000000L(10亿)开始 private static long maxValue = 56800235584L; // 62^6 = 56800235584L (568亿) private static String elements = "G86futKrpN2OgZhTmHX0EiyDnqRvxdCa1SYLQVUzB475IM39ocPJwejkbWslAF"; public static void main(String[] args) { for (long i = minValue; i < minValue+10; i++) { System.out.println(generateStr(i)); } } public static String generateStr(long seq) { if (seq < minValue || seq > maxValue) { System.out.println("超出随机串生成数量!"); return null; } StringBuilder sb = new StringBuilder(); do { int i = (int) (seq % 62); sb.append(elements.charAt(i)); seq /= 62; } while (seq > 0); return sb.reverse().toString(); } }
输出结果:
Connected to the target VM, address: '127.0.0.1:59315', transport: 'socket' 8t4k7m 8t4k7H 8t4k7X 8t4k70 8t4k7E 8t4k7i 8t4k7y 8t4k7D 8t4k7n 8t4k7q Disconnected from the target VM, address: '127.0.0.1:59315', transport: 'socket' Process finished with exit code 0
标签:seq,算法,long,minValue,62,static,随机,字符串,生成 来源: https://www.cnblogs.com/zhlii/p/14314757.html