隨機生成int陣列Demo//ArrayTools
阿新 • • 發佈:2018-12-18
Demo1
/** * @param length * @param start * inclusive. * @param end * exclusive. * @return * @throws NumberWrongException */ public static int[] getRandomInts1(int length, int start, int end) throws NumberWrongException { if (length < 2) throw new NumberWrongException("The length must be larger than 1."); if (start >= end) throw new NumberWrongException("start must be smaller than end."); int range = end - start; if (length > range) throw new NumberWrongException("length must be smaller than range."); Random random = new Random(); int[] numbers = new int[length]; numbers[0] = start + (int) (range * random.nextFloat()); for (int i = 1; i < length; i++) { int temp = start + (int) (range * random.nextFloat()); int j = 0; while (j < i) { if (temp == numbers[j]) { temp = start + (int) (range * random.nextFloat()); j = 0; continue; } j++; } numbers[j] = temp; } return numbers; }
Demo2
/** * * @param length * @param start * inclusive * @param end * exclusive * @return * @throws NumberWrongException */ public static int[] getRandomInts2(int length, int start, int end) throws NumberWrongException { if (length < 2) throw new NumberWrongException("The length must be larger than 1."); if (start >= end) throw new NumberWrongException("start must be smaller than end."); int range = end - start; if (length > range) throw new NumberWrongException("length must be smaller than range."); Random random = new Random(); LinkedList<Integer> ll = new LinkedList<Integer>(); for (int i = start; i < end; i++) { ll.add(i); } int[] numbers = new int[length]; for (int j = 0; j < length; j++) { numbers[j] = ll.remove((int) (random.nextFloat() * ll.size())); } return numbers; }
Demo3 // conbine
/** * @param length * @param start * inclusive. * @param end * exclusive. * @return * @throws NumberWrongException */ public static int[] getRandomInts(int length, int start, int end) throws NumberWrongException { if (length < 2) throw new NumberWrongException("The length must be larger than 1."); if (start >= end) throw new NumberWrongException("start must be smaller than end."); int range = end - start; if (length > range) throw new NumberWrongException("length must be smaller than range."); Random random = new Random(); int[] numbers = new int[length]; if (length * 2 > range) { LinkedList<Integer> ll = new LinkedList<Integer>(); for (int i = start; i < end; i++) { ll.add(i); } numbers = new int[length]; for (int j = 0; j < length; j++) { numbers[j] = ll.remove((int) (random.nextFloat() * ll.size())); } } else { numbers[0] = start + (int) (range * random.nextFloat()); for (int i = 1; i < length; i++) { int temp = start + (int) (range * random.nextFloat()); int j = 0; while (j < i) { if (temp == numbers[j]) { temp = start + (int) (range * random.nextFloat()); j = 0; continue; } j++; } numbers[j] = temp; } } return numbers; }