# generating random numbers in a 5x5 array.

• 08-13-2007, 07:29 PM
acidacid
generating random numbers in a 5x5 array.
hello. :]

so, I've been trying to figure out for the longest time how to generate numbers in my 5x5 matrices without having the numbers repeat themselves more than once.

Code:

```  void Card() {     salida = "";     salida2 = "";     for (i = 0; i <= 4; i++) {       for (j = 0; j <= 4; j++) {         card1[i][j] = 1 + (int) (Math.random() * 99);         if (card1[i][j] <= 9) {           cadena = "0" + card1[i][j];         }         else {           cadena = "" + card1[i][j];         }         salida = salida + " " + cadena;         if (j == 4) {           salida = salida + "\n";         }       }     }     JOptionPane.showMessageDialog(null, salida, "Card 1",                                   JOptionPane.INFORMATION_MESSAGE); }```
this what I have for the array. I've had plenty more, but I tried to many different methods to solve my problem, and none of it really helped. your help would be greatly appreciated. :]

oh and I apologize about the spanish variables, but i'm still sure the code still is understandable. :]
• 08-13-2007, 08:45 PM
dmacvittie
Since this all looks okay, I presume it is the non-repeating part you're struggling with?

The best solution to that problem AFAIK is brute force - write a method that loops through the list and returns true if it is a duplicate or false if not. put that routine and the generation of the next random into a loop until it returns false, and only then assign the value into the array.
Code:

```boolean isDuplicate = true; while(isDuplicate) {   card[i][j]=1 + (int) (Math.random() *99);   isDuplicate = checkDuplicate(card1, i, j); }```
Then the isDuplicate method has to walk the array and compare the element at i,j with everything until it either finds a match (returning true) or runs out of elements (returning false).

No worries about variable names ;). I don't apologize for making you read them in English, you shouldn't for returning the favor.

Hope that helps,
Don.
• 08-14-2007, 03:07 AM
acidacid
Quote:

Originally Posted by dmacvittie
Code:

```boolean isDuplicate = true; while(isDuplicate) {   card[i][j]=1 + (int) (Math.random() *99);   isDuplicate = checkDuplicate(card1, i, j); }```

umm... checkDuplicate is giving me a "cannot resolve symbol." is there any way I can initialize it or declare it as a variable or something? : D

other than that I understood everything perfectly, and I thank you very much for the help you provided. <333
• 08-14-2007, 03:44 AM
dmacvittie
You have to write it, just iterate through the array and look for a match with the new number.

Don.