How to generate a pair of random number from 1 to 8 that can fill into a 2D array in a 4x4 square?
For example:

2 3 5 6
1 7 8 3
5 4 1 6
7 2 4 8

Random r = new Random();
int[][] 2dArray = new int[4][4];
for (int i = 0; i<4; i++){
   for (int j = 0; j<4; j++){
      2dArray[i][j] = r.nextInt(8) + 1; 
      // nextInt returns a random int >= 0 and < n
   }
}
Random r = new Random();
int[][] 2dArray = new int[4][4];
for (int i = 0; i<4; i++){
   for (int j = 0; j<4; j++){
      2dArray[i][j] = r.nextInt(8) + 1; 
      // nextInt returns a random int >= 0 and < n
   }
}

Thx...
But how I gona to make sure every number from 1 to 8 are come out in a pairs?

Can you be more specific? how exactly in pairs ?

Sory, my english not very gud...
I mean a pair of random number is like the program will generate a match of number that from 1 to 8 like the example below...

2 5 1 3
3 8 7 6
1 2 4 5
4 6 8 7

All number must come out in a pair, because I need to write a program that plays the memory matching game.

I don't know if it's the best idea but that's what I got at a late hour :yawn: :

Create an array of size 8 which will hold the times each number 1 .. 8 was generated so far, and initialize it with 0's (we have no generated numbers):

int[] t = new int[8];
for (int i=0; i<8; i++){
   t[i] = 0;
}

then when a number is generated increment his corespondent in this array (t[0] for 1, t[1] for 2, ... ). If the number has been generated twice then generate another number, else put it in the 2D array and increment his value in t array.

Random r = new Random();
int[][] 2dArray = new int[4][4];
int number;
for (int i = 0; i<4; i++){
   for (int j = 0; j<4; j++){      
      number = r.nextInt(8) + 1; // generate a number
      while (t[number-1] == 2){ 
      // if the number was already generated 2 times
          number = r.nextInt(8) + 1; // generate another number
      }
       // we have a number that was NOT generated 2 times
       // add it to 2D array
       2dArray[i][j] = number;
       // increment the times he was generated
       t[number-1] = t[number-1] + 1; 
       // number-1 because the index of an array starts from 0, not from 1
   }
}

Oh when you say pair you mean in an 2d array like structure?

Like so :

Random generate= new Random();
int[][] Array2d = new int[4][4];
for (int row = 0; row < Array2d.length; row++){
   for (int col = 0; col < Array2d[row].length; col++){
      Array2d[row][col] = generate.nextInt(8) + 1; // [0,8)
   }
  System.out.print("\n");
}

So the above code might print out :

1 2 5 1
5 1 2 3
4 6 1 7
1 3 1 2

Edited 6 Years Ago by firstPerson: n/a

Here is how you can generate a random number between two numbers:

public static int random(int min, int max) {
        double rand = Math.random();
        rand *= max - min;
        rand += min;

        return (int) rand;
    }
This question has already been answered. Start a new discussion instead.