生成位随机不重复的数字编号 package monutil; import javautilArrays; import javautilRandom; /** * */ public class RandomNumberGenerator { /** * 这是典型的随机洗牌算法 * 流程是从备选数组中选择一个放入目标数组中将选取的数组从备选数组移除(放至最后并缩小选择区域) * 算法时间复杂度O(n) * @return 随机为不重复数组 */ public static String generateNumber() { String no=; //初始化备选数组 int[] defaultNums = new int[]; for (int i = ; i < defaultNumslength; i++) { defaultNums[i] = i; } Random random = new Random() int[] nums = new int[LENGTH]; //默认数组中可以选择的部分长度 int canBeUsed = ; //填充目标数组 for (int i = ; i < numslength; i++) { //将随机选取的数字存入目标数组 int index = randomnextInt(canBeUsed) nums[i] = defaultNums[index]; //将已用过的数字扔到备选数组最后并减小可选区域 swap(index canBeUsed defaultNums) canBeUsed; } if (numslength>) { for (int i = ; i < numslength; i++) { no+=nums[i]; } } return no; } private static final int LENGTH = ; private static void swap(int i int j int[] nums) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public static String generateNumber() { String no=; int num[]=new int[]; int c=; for (int i = ; i < ; i++) { num[i] = new Random()nextInt() c = num[i]; for (int j = ; j < i; j++) { if (num[j] == c) { i; break; } } } if (numlength>) { for (int i = ; i < numlength; i++) { no+=num[i]; } } return no; } public static void main(String[] args) { for (int i = ; i < ; i++) { // Systemoutprintln(generateNumber()) Systemoutprintln(generateNumber()) } } } |