在Java中生成范围内的非重复随机数 [英] Generate non repeating random number within range in Java

查看:151
本文介绍了在Java中生成范围内的非重复随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成1到4,4范围内的随机数,包括。

这是我的代码:

I want to generate random numbers within the range 1 to 4, 4 including.
Here is my code:

int num = r.nextInt(4) + 1;  //r is instance of Random.

但是,我在循环中运行上面的代码,不想重复随机数。
现在经常发生的事情通常是我得到的:

1,1,1,2,3,1,4,2,2,1,4,2, 4,4,2,1,4,3,3,1,4,2,4,1 作为我的输出。

However, I am running the above code in a loop and don't want repeating random number. What happens now is often I am getting:
1,1,1,2,3,1,4,2,2,1,4,2,4,4,2,1,4,3,3,1,4,2,4,1 as my output.

这里虽然数字在范围(1-4)内是随机的,但经常像前3次迭代中的数字1一样重复。


我正在寻找的是一种获得非重复随机的方法循环中的数字。
我知道的一个简单方法是在当前迭代之前保留最后一个随机数并进行比较,但我相信必须有更好的解决方案。

提前谢谢。

Here, though the numbers are random within the range(1-4), but often repeated like the number "1"in the first 3 iterations.

What I am looking for is a way to get non repeating random number within the loop. One simple way I know is of keeping the last random number before current iteration and compare, but I am sure there must be better solution to this.
Thanks in advance.

推荐答案

使用 random.nextInt(range-1)然后将该数字映射到输出具有排除前一个数字的函数的数字:

Use random.nextInt(range-1) and then map that number to the output number with a function that excludes the previous number:

public class Test {
  private final Random random = new Random();
  private final int range;
  private int previous;

  Test(int range) { this.range = range; }

  int nextRnd() {
    if (previous == 0) return previous = random.nextInt(range) + 1;
    final int rnd = random.nextInt(range-1) + 1;
    return previous = (rnd < previous? rnd : rnd + 1);
  }


  public static void main(String[] args) {
    final Test t = new Test(4);
    for (int i = 0; i < 100; i++) System.out.println(t.nextRnd());
  }
}

这篇关于在Java中生成范围内的非重复随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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