爪哇 - 生成特定的数字随机范围,而这些数字的重复 - 如何? [英] Java - generate Random range of specific numbers without duplication of those numbers - how to?

查看:187
本文介绍了爪哇 - 生成特定的数字随机范围,而这些数字的重复 - 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听起来很简单......但我一直在刻苦这一点,试图找到一个和所有的解决方案。

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.

然后,我希望把这些随机的号码变成阵列,并使用该数组在随机选择和显示一些项目(如库存从数据库中抽取)上一个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.

有一个简单的解决这个问题?

测试#1使用收藏洗牌()法 -

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>");
}

结果是就像使用 Col​​lections.shuffle()

推荐答案

您可以填写从1所有值的数组到12,然后打乱它们(例如见的集合洗牌()

You can fill an array with all values from 1 to 12 and then shuffle them (see e.g. Collections shuffle())

这篇关于爪哇 - 生成特定的数字随机范围,而这些数字的重复 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆