【发布时间】:2016-04-27 17:22:58
【问题描述】:
我需要选择两个不同的整数,它们属于某个范围[min, max]。
示例:rds = 3、min = 0、max = 9。如果第一个随机元素是r1 = 6,那么r2必须不同于6,r3必须不同于r1和r2。
我想构建一个包含所有属于[min, max] 的数字的数组:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]。
我在0 和9 之间选择一个随机数并返回ThreadLocalRandom.current().nextInt(0, 10),然后我交换r1 和数组的最后一个元素。
为了找到r2,我将0中的随机函数应用到数组中的倒数第二个位置,依此类推。
这是代码:
public void takeRandomXposition(int rds, int[] positions) {
int k = positions.length;
int min = 0;
int max = k - 1;
for(int i = 0; i < rds; i++) {
int r = random(positions[min], positions[max - i]);
swapPositions(positions, r, max - i);
}
}
public int random(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
public void swapPositions(int[] positions, int index, int last) {
int indexA = positions[index];
int lastA = positions[last];
positions[index] = lastA;
positions[last] = indexA;
}
此方法适用于第一步,但不再适用。 问题是数组中的元素被移动和混合,但我尝试了一个范围内的随机数。 不知道怎么解释,我举个例子说明方法不行。
positions: [ 0 1 2 3 4 5 6 7 8 9 ]
rds = 3
k = 10
min = 0
max = 9
i = 0
search r in range [0, 9]
r = 5
positions: [ 0 1 2 3 4 9 6 7 8 5 ]
i = 1
search r in range [0, 8]
r = 3
positions: [ 0 1 2 8 4 9 6 7 3 5 ]
i = 2
search r in range [0, 7]
r = 5
positions: [ 0 1 2 8 4 7 6 9 3 5 ]
另外r = 0时还有一个问题:
positions: [ 0 1 2 3 4 5 6 7 8 9 ]
rds = 3
k = 10
min = 0
max = 9
i = 0
search r in range [0, 9]
r = 0
positions: [ 9 1 2 3 4 5 6 7 8 0 ]
i = 1
search r in range [9, 8]
Exception in thread "main" java.lang.IllegalArgumentException: bound must be greater than origin
所以,我不想在[min, max] 范围内找到一个随机数,而是在一个数组的内容中找到一个随机数。
谢谢。
【问题讨论】:
-
为什么不使用简单的数学公式创建一个表示特定范围内数组的数字(索引)的方法(以控制 indexOutOfBoundException)?!
-
@MR1 对不起,我没明白你的意思。
-
据我了解您的问题,您希望随机访问数组的内容,为此您需要访问数组的特定元素,因此通过指定该方法,您可以访问随机元素数组。