# Thread: Can I prevent random numbers from repeating in a 2d array

1. Member
Join Date
Apr 2011
Posts
3
Rep Power
0

## Can I prevent random numbers from repeating in a 2d array

Is there a way to Stop repeating random numbers in a 2d array?

I have a 2d array 5x3 and I need to prevent a random number from repeating in the middle column which is array[r][1]
Here's what I have...

public static void main(String[] args)
{
int MyArray[][] = new int [5][3];
fillArray(MyArray);
OutputArray(MyArray); //method to display array
}//end of main

static void fillArray(int array[][])
{
for (int r=0; r<array.length; r++)
{
for (int c=0; c<array[0].length; c++)
{
array[r][c] = (int)(Math.random()*10000)%10+1;
}//end of column
}//end of row
}//end of fillArray

I can make the element at array[1][1] not equal to array[0][1] but this means alot of coding to ensure all scenarios in this row do not equal each other.
Is there an easy way?

Any help greatly appreciated.

2. Use a Set. Fill the Set up with random numbers until you have enough to fill your array. Then populate your array with those numbers.

3. Member
Join Date
Apr 2011
Posts
3
Rep Power
0
Thanx for the quick reponse.

Sorry I'm a noob to Java and I haven't yet come to Set.

I was hoping for some answer to include a loop, a swap, an if statement or combination of these or something similar.

4. Try it.
Post your best effort.
Ask a specific question about any problem you face.

db

5. In that case, then you already know what you have to do. Write the code that loops through the array up to the current index, and only add the number if it hasn't already been added.

6. Member
Join Date
Apr 2011
Posts
3
Rep Power
0
"if it hasn't already been added" This is where I'm having problems. I've tried many variations with if statements, while loops and do while loops but I cant seem to identify if an integer has been assigned to a previous element.

for(int c=1; c<array[0].length-1; c++)
{
for(int r=0; r<array.length; r++)
{
if (array[r][c] != array[r][c])
array[r][c] = (int)(Math.random()*10000)%10+1;

}// end of row for loop
} // end of column for loop

Thanx for any help

7. Write a method that checks whether a certain item is in the array. Call that method before setting the value of the current index.

8. Member
Join Date
Mar 2011
Posts
48
Rep Power
0
I usually just create a counter that counts from 1 to n add them to an arraylist then do a shuffle on them. Probably not as elegant as the Set method since a set doesnt allow duplicat numbers. But thats how I did it before I discovered Set s

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•