简体   繁体   中英

Random number generator without repetition Class in Java

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

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();

And the result is: 0,0,0,0,0,0.... For range (5,10) the result is 5,5,5,5....

Does anybody knows what is wrong with the code? I would really appreciate any help!

Thank you in advance.

I guess this line is issue.

int index = size * (int) Math.random();

This evaluates to Zero always.

Edit:

Just consolidating comments from Jeroen Vannevel and OP.

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());

You should try using Random class:

http://developer.android.com/reference/java/util/Random.html

Random random = new Random();
int randomNo = random.nextInt(10);  // 0 to 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM