samedi 10 août 2019

Printing Non Repeating Random Numbers within a range

I am trying to write a simple random number generator class that will print non duplicate numbers within a given range of max and min. I have the logic all down and I am using a set as well however I still get some repeating numbers. The idea is that if I declare min and max to be 0 and 5 I should get random numbers like 2 3 1 5 4 0. Then it can reset and give me the numbers again randomly within the range without repetition. See code below

package RandomNumGenerator;

import java.util.*;

public class RandomNumberGenerator {

int minimum;
int maximum;
Random random = new Random();

public RandomNumberGenerator(int min, int max)
{
    minimum = min;
    maximum = max;
}

public void printRandomNumber()
{
    Set<Integer> hSet =  new HashSet<>();
    int range =  maximum - minimum + 1; 
    int randomValue = 0; 

    while(hSet.size() < range)
    {
        randomValue =  minimum + random.nextInt(maximum - minimum + 1); 
        hSet.add(randomValue);
    }

    System.out.println("The next random number is: " + randomValue);    
}


public static void main(String[] args)
{

    RandomNumberGenerator rng = new RandomNumberGenerator(5, 10);
    rng.printRandomNumber();
    rng.printRandomNumber();
    rng.printRandomNumber();
    rng.printRandomNumber();
    rng.printRandomNumber();
    rng.printRandomNumber();

}
}

Currently in my output I am getting this despite using a HashSet to remove non repeating integers: I am expecting something like 10 8 7 5 9 6 but instead I get

The next random number is: 9

The next random number is: 6

The next random number is: 8

The next random number is: 9

The next random number is: 6

The next random number is: 8




Aucun commentaire:

Enregistrer un commentaire