随机数发生器没有在Java中的重复类 [英] Random number generator without repetition Class in Java
问题描述
首先,我是一个新手,Android应用程序开发者。在我的应用程序,我需要这在一个给定的范围内避免重复产生随机数的类。我搜索了很多这个问题,但我还没有发现我的情况下,任何具体的解决方案。好了,以为我找到了一个我稍微重新适应,但它无法正常工作。在code是下列之一:
First of all, I'm a newbie Android App developer. In my App I need a class which generates random numbers in a given range avoiding repetition. I've searched much for this issue, but I haven't found any concrete solution for my case. Well, thought I found one which I slightly readapt, but it's not working fine. The code is the following one:
public class NoRepeatRandom {
private int[] number = null;
private int N = -1;
private int size = 0;
public NoRepeatRandom(int minVal, int maxVal)
{
N = (maxVal - minVal) + 1;
number = new int[N];
int n = minVal;
for(int i = 0; i < N; i++)
number[i] = n++;
size = N;
}
public void Reset() { size = N; }
// Returns -1 if none left
public int GetRandom()
{
if(size <= 0) return -1;
int index = size * (int)Math.random();
int randNum = number[index];
// Swap current value with current last, so we don't actually
// have to remove anything, and our list still contains everything
// if we want to reset
number[index] = number[size-1];
number[--size] = randNum;
return randNum;
}
}
当我请GetRandom()本人没有达到预期的结果,因为它总是返回给定的范围内的最小数目。例如:
When I call GetRandom() I don't achieve the expected result, because it always returns the minimum number of the range given. For example:
NoRepeatRandom nrr = new NoRepeatRandom(0, 10);
int yes = nrr.GetRandom();
//Here I create a Toast just to see the numbers that the method is returning.
Toast toast = Toast.makeText(MainActivity.this, Integer.toString(yes), Toast.LENGTH_SHORT);
toast.show();
和结果是:0,0,0,0,0,0 ....
对于范围(5,10),结果是5,5,5,5 ....
And the result is: 0,0,0,0,0,0.... For range (5,10) the result is 5,5,5,5....
有谁知道什么是错的code?我真的AP preciate任何帮助!
Does anybody knows what is wrong with the code? I would really appreciate any help!
感谢您提前。
推荐答案
我想这条线是问题。
int index = size * (int) Math.random();
该计算结果为零始终。
编辑:
刚刚合并来自吉荣Vannevel和OP的意见。
Just consolidating comments from Jeroen Vannevel and OP.
的Math.random( )将返回在0.0和1.0之间的值,当其与 CAST(INT)
将始终计算结果为零。您ca的如下使用。
Math.random() will return a value between 0.0 and 1.0, which when cast with (int)
will always evaluates to ZERO. You ca use as below.
int index = (int) (size * Math.random());
这篇关于随机数发生器没有在Java中的重复类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!