Java - 生成特定数字的随机范围而不重复这些数字 - 如何? [英] Java - generate Random range of specific numbers without duplication of those numbers - how to?
问题描述
听起来很简单……但我一直在努力解决这个问题,试图找到唯一的解决方案.
Sounds simple enough...but I've been plugging away at this, trying to find the one and all solution.
对于一系列数字,比如 1-12,我想在该范围内生成一个随机序列,和包括 1 和12.
For a range of numbers, say 1-12, I want to generate a random sequence within that range, and include 1 and 12.
我不想要重复的数字.
所以我想要这样的东西 - 3,1,8,6,5,4 ..等等,从 1 到 12 的每个数字.
So I would want something like this - 3,1,8,6,5,4 ..and so on, every number from 1-12.
然后我想将这些随机数放入一个 Array
并使用该数组在 jsp 页面上随机"选择和显示一些项目(如从数据库中提取的库存).
Then I want to put these random numbers into an Array
and use that array to 'randomly' select and display some items (like inventory pulled from database) on a jsp page.
到目前为止我所尝试的问题是,有很多重复数字正在生成......或者,不是所有数字是选择了.
The problem with what I've tried thus far, is that there are a lot of duplicate numbers being generated...or, not ALL of the numbers are chosen.
这个问题有简单的解决方法吗?
Test#1 使用 Collections
和 shuffle()
方法 -
Test#1 using Collections
and shuffle()
method -
ArrayList<Integer> list = new ArrayList<Integer>(10);
for(int i = 0; i < 10; i++)
{
list.add(i);
}
Collections.shuffle(list);
String[] randomNumbers = (String[])list.toArray();
for(int i = 0; i < 10; i++)
{
out.print(randomNumbers[i]+"<br>");
}
结果是一个带有重复值的序列 -
选择 = 3
选择 = 8
选择 = 7
选择 = 5
选择 = 1
选择 = 4
选择 = 6
选择 = 4
选择 = 7
选择 = 12
The result was a sequence with duplicate values -
chose = 3
chose = 8
chose = 7
chose = 5
chose = 1
chose = 4
chose = 6
chose = 4
chose = 7
chose = 12
测试 #2 - 使用随机数学课
int max = 12;
int min = 1;
int randomNumber = 0;
String str_randomNumber = "";
for(int i=0; i<10; i++) {
//int choice = 1 + Math.abs(rand.nextInt(11));
int choice = min + (int)(Math.random() * ((max - min) + 1));
out.print("chose = "+choice+"<br>");
}
结果就像使用 Collections.shuffle()
.
推荐答案
您可以使用 1 到 12 之间的所有值填充数组,然后将它们打乱(参见例如 为什么我的数组的 Collections.shuffle() 失败?)
You can fill an array with all values from 1 to 12 and then shuffle them (see e.g. Why does Collections.shuffle() fail for my array?)
这篇关于Java - 生成特定数字的随机范围而不重复这些数字 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!