生成特定范围内的随机数
Generating random numbers in a particular range
我正在尝试在我的 Android 代码中生成 n
0-31 之间的随机数。
下面是我正在使用的代码:
int max_range = 31;
SecureRandom secureRandom = new SecureRandom();
int[] digestCodeIndicesArr = new int[indices_length];
int i = 0, random_temp = 0;
while (i != indices_length-1) {
random_temp = secureRandom.nextInt(max_range);
if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp)) {
digestCodeIndicesArr[i] = random_temp;
i++;
}
}
indices_length
是我需要的随机数的个数。它通常是 6,7 或 9。但是当我打印生成的数组时,我通常会看到重复项。有人可以指出我犯的错误。我添加了以下代码行以过滤掉随机重复项:
if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))
提前致谢!
Arrays.asList(digestCodeIndicesArr)
不会生成 List<Integer>
和 size() == digestCodeIndicesArr.length
。
它产生一个 List<int[]>
和 size() == 1
,其中第一个(也是唯一的)元素是数组。
因此,它永远不会包含 random_temp
,因此 ! contains()
始终为真。
不断创建列表并执行顺序搜索以检查重复项对性能不利。请改用 Set
,与数组并行维护,或先使用 LinkedHashSet
,然后转换为数组。
无论如何,这解释了为什么您的代码无法正常工作。 Tunaki 提供的副本 link 和我在评论中提供的 duplicate link 解释了如何实际做你想做的事情。
您需要更改:
int[] digestCodeIndicesArr = new int[indices_length];
至:
Integer[] digestCodeIndicesArr = new Integer[indices_length];
因为 Arrays.asList(digestCodeIndicesArr)
是 List<int[]>
,可能不是你想的那样(我猜是 List<int>
或 List<Integer>
)。
我正在尝试在我的 Android 代码中生成 n
0-31 之间的随机数。
下面是我正在使用的代码:
int max_range = 31;
SecureRandom secureRandom = new SecureRandom();
int[] digestCodeIndicesArr = new int[indices_length];
int i = 0, random_temp = 0;
while (i != indices_length-1) {
random_temp = secureRandom.nextInt(max_range);
if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp)) {
digestCodeIndicesArr[i] = random_temp;
i++;
}
}
indices_length
是我需要的随机数的个数。它通常是 6,7 或 9。但是当我打印生成的数组时,我通常会看到重复项。有人可以指出我犯的错误。我添加了以下代码行以过滤掉随机重复项:
if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))
提前致谢!
Arrays.asList(digestCodeIndicesArr)
不会生成 List<Integer>
和 size() == digestCodeIndicesArr.length
。
它产生一个 List<int[]>
和 size() == 1
,其中第一个(也是唯一的)元素是数组。
因此,它永远不会包含 random_temp
,因此 ! contains()
始终为真。
不断创建列表并执行顺序搜索以检查重复项对性能不利。请改用 Set
,与数组并行维护,或先使用 LinkedHashSet
,然后转换为数组。
无论如何,这解释了为什么您的代码无法正常工作。 Tunaki 提供的副本 link 和我在评论中提供的 duplicate link 解释了如何实际做你想做的事情。
您需要更改:
int[] digestCodeIndicesArr = new int[indices_length];
至:
Integer[] digestCodeIndicesArr = new Integer[indices_length];
因为 Arrays.asList(digestCodeIndicesArr)
是 List<int[]>
,可能不是你想的那样(我猜是 List<int>
或 List<Integer>
)。