0

So I am generating random coordinates on a given grid that contains x number of rows and y number of columns. Let's say I want to generate 25 random numbers on a 8 by 6 grid.(8 columns, 6 rows) I wrote piece of code like this and it is only partially working because this code does not excludes duplicates:

    int intputRows =6;
    int inputColumns=8;
    Random randomNumGenerator = new Random();
        for(int i=0;i<25;i++){
            int randomRows = randomNumGenerator.nextInt(inputRows);
            int randomColumns = randomNumGenerator.nextInt(inputColumns);
        }

My question is, how do I avoid to generate duplicate numbers? I understand there are ways like put those in a List structure and shuffle, but could I done it with Random generator?

OPK
  • 4,120
  • 6
  • 36
  • 66
  • Please search before psoting. – T.J. Crowder Aug 02 '15 at 17:53
  • @T.J.Crowder I have taken a closer look at the question you marked as duplicate, in fact I do not think they are the same. The answer only provides a way to deal with one random numbers, which is fine when using `Set`, my question needs to handle two random numbers, in this case it does not work with a `Set`, please consider reopen the question. – OPK Aug 02 '15 at 19:55

2 Answers2

1

Just use a Set:

int intputRows =6;
int inputColumns=8;
HashSet<Integer> set = new HashSet<>();
Random randomNumGenerator = new Random();
int temp;
    for(int i=0;i<25;i++){
        temp = randomNumGenerator.nextInt(inputRows);
        if(set.add(temp))
            int randomRows = temp;
        temp = randomNumGenerator.nextInt(inputRows);
        if(set.add(temp))
            int randomColumns = temp;
    }

You still have to implement an else, in case it already exists, but I just gave you the idea.

Mordechai
  • 15,437
  • 2
  • 41
  • 82
0

Simple add the numbers to a Set, for example a HashSet, which cannot contain duplicate values, until your Set hat the desired length.

Set<Integer> randomNumbers = new HashSet<Integer>();
while(randomNumbers.size() < 25) {
    randomNumbers.add( randomNumGenerator.nextInt(inputRows) );
}

Of course some checks would be nice to test that there is a chance that the code will finish, etc.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58