package random; public class RandomRepeatOrNotRepeat { // 随机数字最大值 public final static int maxValue = 11; // 随机数字最小值 public final static int minValue = 1; // 需要几位数字 public final static int resultLength = 5; // 生成多少行 public final static int rows = 10; public static void main(String args[]) { // 不重复随机,将已经随机到的下标移动到最后一个,减少数组长度 three(); // 不重复随机,标记数组中的值 // two(); // 普通随机 // one(); } public static void three() { int[] a = new int[maxValue]; int[] result = new int[resultLength]; for (int j = 0; j < rows; j++) { a = new int[maxValue]; init(a); for (int i = 0; i < resultLength; i++) { int random = (int) (Math.random() * a.length); swap2tail(a, random); result[i] = a[a.length - 1]; a = decreaseLength(a); } for (int i = 0; i < result.length; i++) System.out.print(result[i] + ","); System.out.println(); } } private static int[] decreaseLength(int[] a) { int[] result = new int[a.length - 1]; for (int i = 0; i < result.length; i++) result[i] = a[i]; return result; } private static void swap2tail(int[] a, int random) { if (random == a.length - 1) return; a[random] ^= a[a.length - 1]; a[a.length - 1] ^= a[random]; a[random] ^= a[a.length - 1]; } private static void init(int[] a) { for (int i = 0; i < a.length; i++) a[i] = i + minValue; } public static void two() { for (int j = 0; j < rows; j++) { int[] a = new int[maxValue]; for (int i = 0; i < resultLength; i++) { int random = (int) (Math.random() * maxValue); markA(a, random); } printValueNotOne(a); } } private static void printValueNotOne(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] != 0) System.out.print(i + minValue + ","); } System.out.println(); } public static void markA(int[] a, int random) { if (a[random] == 0) { a[random] = 1; return; } markA(a, (random + 1) % a.length); } public static void one() { String s = ""; for (int j = 0; j < rows; j++) { for (int i = 0; i < resultLength; i++) { s += ((int) (Math.random() * maxValue + minValue)) + ","; } System.out.println(s); s = ""; } } public static void printTestArray(int[] a) { System.out.println("----------- Test -----------"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + ","); System.out.println(); System.out.println("----------- Test -----------"); } }
原文地址:http://blog.csdn.net/tragedyxd/article/details/46390343