Generate numbers for a matrix in java

0

I need to generate random numbers from 3 to 10 in a matrix of 8x8 without repeating them and since the matrix is something big the other numbers should be placed in 0

an example

{0,0,0,0,0,6,0,0}
{0,0,3,0,0,0,0,0}
{0,0,0,0,0,0,0,9}
{0,0,0,4,0,0,0,0}
{0,0,0,0,0,0,7,0}
{0,0,5,0,0,0,0,0}
{0,0,0,0,0,8,0,0},
{10,0,0,0,0,0,0,0}
    
asked by MZ39720 03.12.2018 в 16:02
source

2 answers

-1

We are going to turn the problem around. As I see it, you do not need random numbers from 3 to 10. You ALWAYS need that sequence of numbers, but placed randomly within the 8x8 matrix.

What I would do, then, is a cycle that gives me the sequence of numbers from 3 to 10, and for each one, I generate a random position and, if it is not already occupied by another number, I assign it the value of the sequence. If you are already busy, I repeat the process until I find one that is not.

In code, it would be something like:

  public static void main (String args[]) {
    int FILAS = 8;
    int COLUMNAS = 8;

    int[][] matriz = new int[FILAS][COLUMNAS];

    Random aleatorio = new Random();
    boolean asignado;
    for (int i = 3; i != 10; i++) {
      asignado = false;
      do {
        int fila = aleatorio.nextInt(FILAS);
        int columna = aleatorio.nextInt(COLUMNAS);
        if (matriz[fila][columna] == 0) {
          matriz[fila][columna] = i;
          asignado = true;
        } 
      } while (!asignado);
    }
    for (int i = 0; i < FILAS; i++) {
      for (int j = 0; j < COLUMNAS; j++) {
        System.out.print(matriz[i][j] + ", ");
      }
      System.out.print("\n");
    }
  }

What it produces for me, for example, is exit:

0, 9, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 
0, 4, 0, 0, 0, 0, 0, 0, 
0, 5, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 7, 
0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 3, 0, 0, 
6, 0, 0, 8, 0, 0, 0, 0, 
    
answered by 03.12.2018 / 17:11
source
0

To generate the random numbers you can use java.util.Random

This code stores the 8 random numbers in a vector. From there you can place them in the matrix applying your own criteria.

int [] aleatorios = new int[8];
Random random = new Random();
for(int i=0;i<8;i++){
    aleatorios[i] = random.nextInt(8) + 3;
}
    
answered by 03.12.2018 в 16:46