MCPcopy Index your code
hub / github.com/hustcc/JS-Sorting-Algorithm / randomArray

Method randomArray

src/java/test/ArraySortTest.java:46–71  ·  view source on GitHub ↗

随机指定范围内N个不重复的数 在初始化的无重复待选数组中随机产生一个数放入结果中, 将待选数组被随机到的数,用待选数组(len-1)下标对应的数替换 然后从len-2里随机产生下一个随机数,如此类推 @param max 指定范围最大值 @param min 指定范围最小值 @param n 随机数个数 @return int[] 随机数结果集

(int min, int max, int n)

Source from the content-addressed store, hash-verified

44 * @return int[] 随机数结果集
45 */
46 public int[] randomArray(int min, int max, int n) {
47 int len = max - min + 1;
48
49 if (max < min || n > len) {
50 return null;
51 }
52
53 //初始化给定范围的待选数组
54 int[] source = new int[len];
55 for (int i = min; i < min + len; i++) {
56 source[i - min] = i;
57 }
58
59 int[] result = new int[n];
60 Random rd = new Random();
61 int index = 0;
62 for (int i = 0; i < result.length; i++) {
63 //待选数组0到(len-2)随机一个下标
64 index = Math.abs(rd.nextInt() % len--);
65 //将随机到的数放入结果集
66 result[i] = source[index];
67 //将待选数组中被随机到的数,用待选数组(len-1)下标对应的数替换
68 source[index] = source[len];
69 }
70 return result;
71 }
72
73 @After
74 public void tearDown() throws Exception {

Callers 1

setUpMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected