# Thread: Unique Random Numbers in 2D Array

1. ## Unique Random Numbers in 2D Array

I am a beginer. I have been able to place unique random numbers into an array but I am having trouble placing them in 2D array. How do I do that? Can u show me?

here is my simple code

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int array[7];
int i;

for (i=0; i<=7; i++)
array[i] = i;

srand( (unsigned)time( NULL ) );
for (i=0; i<=7; i++)
{
int index1 = i;
int index2 = rand()%7;

int temp;
temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

for (i=0; i<=7; i++)
printf("array[%d] = %d\n",i,array[i]);

return(0);
}```

2. For a 2D array, you do the same thing as for a 1D. It might be easier to think of the 2D array as "lined up" as a 1D array. That is, imagine assigning each element in the array with a single index. Then you take the index, and extract the row and column numbers. One way to do this is to use / and % operators. For example, to randomly pick any position in a 5x8 array and set it to zero, you could use this:

int pos = rand % 40; // We imagine the array is a 1-D array of 40 (5*8) elements

int r = pos / 8; // we get the row by division by the # of columns
int c = pos % 8; // We get the column by modulus by the # of columns

array[r][c] = 0;

If we think of our array, this is how our imaginary indices map to real ones:

Code:
```real col: 00 01 02 03 04 05 06 07
real row -------------------------
00| 00 01 02 03 04 05 06 07
01| 08 09 10 11 12 13 14 15
02| 16 17 18 19 20 21 22 23
03| 24 25 26 27 28 29 30 31
04| 32 33 34 35 36 37 38 39```
For example, notice 29 of our "imaginary" index maps to row # 3 (29/8) and col # 5 (29 % 8)

You can use any algorithm that works on a 1D array on a 2D array if you use this method. There is a way you can use a similar method for 3D, 4D, or any arbitrary number of dimentions, but it's more complex for those. The 2D case is pretty straightforward.

3. Code:
```int my_array[5][10];

for(int i=0; i<5; i++)
{
for(int j=0; j<10; j++)
{
my_array[i][j] = 10;   //or a random number you generate
}
}```