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

• 04-20-2011, 01:57 PM
GerB68
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.
• 04-20-2011, 02:04 PM
KevinWorkman
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.
• 04-20-2011, 02:12 PM
GerB68
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.
• 04-20-2011, 02:15 PM
DarrylBurke
Try it.

db
• 04-20-2011, 02:16 PM
KevinWorkman
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.
• 04-20-2011, 04:20 PM
GerB68
"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
• 04-20-2011, 05:01 PM
KevinWorkman
Write a method that checks whether a certain item is in the array. Call that method before setting the value of the current index.
• 04-22-2011, 11:40 AM
sibernewf
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