Display an array of diagonals with even numbers

0

I have a problem that involves matrices, what I need to do is fill a matrix of N * M of dimension (that is, of a number n of columns and rows given by the user), with even numbers, which already huh got. My inconvenience is generated when I am going to deploy this matrix, since when the number of rows is greater than that of the columns, I have an error which is this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1     at diagonal.pkg2.Diagonal2.main (Diagonal2.java:40) D: \ Users \ Jefferson \ AppData \ Local \ NetBeans \ Cache \ 8.2 \ executor-snippets \ run.xml: 53: Java returned: 1

But, otherwise, when the matrix is of form n * m and the rows do not exceed the one of the columns or it is square, there is no problem Attached runs of each case:

run when the number of rows is greater than the number of columns

Here is another problem too, since just after its main diagonal, all its values are zero (which should not be the case)

run of the program, when the number of rows is less than the number of columns and the error

How can I solve these problems? I leave the code:

   int filas;
int columnas;
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Ingrese el nro de filas para la matriz: ");
filas=Integer.parseInt(br.readLine());
System.out.println("Ingrese el nro de columnas para la matriz: ");
columnas=Integer.parseInt(br.readLine());

//definimos las variables para almacenar la matriz y de control
int fila, columna, ultimaColumnaInicio, ultimaFilaInicio;
int matriz[][];
int valor = 2;
matriz = new int[filas][columnas];

ultimaColumnaInicio = columna = columnas - 1;
ultimaFilaInicio = fila = 0;
do {
  matriz[fila++][columna++] = valor;
  if (columna == columnas) {
    fila = 0;
    columna = --ultimaColumnaInicio;
  } else if (fila == filas) {
    fila = ++ultimaFilaInicio;
    columna = 0;
  }
  valor = valor + 2;
} while ((fila != filas));


for(int i=0; i < filas; i++) {
    for(int j=0; j < columnas; j++) {
        System.out.print(String.format("%3d", matriz[i][j]) +" ");
    }
    System.out.println("");
}  
    
asked by Axwell Duarte 23.11.2018 в 04:00
source

1 answer

1

I achieved a solution using coordinates, variables X e Y that will go 'moving'; if we see that route we realize that there is a single pattern of movement, up and down diagonally.

That suggests putting X=-1 e Y=cols-2 or if the array has a single column Y=0 to later perform that single movement pattern of the form X++; Y++; ( up-down diagonally to the right ).

In addition to this verify and correct if our coordinate is outside the dimensions of the matrix.

/*Si las coordenadas están por fuera se utiliza este método:
 *Coloca a X en la primera fila, después para Y busca posiciones
 *que estén en 0 (desocupadas), si no las encuentra, Y llegaría a -1
 *entonces procederia a corregir: X avanza 1 fila e Y pasa a la primera columna.
 */
private void tracking() {
    X=0;
    Y = cols > 1 ? cols-2 : 0;
    while(M[X][Y]!=0) {
      Y--;
      if(Y==-1) {
        X++;
        Y=0;
      }
    }
  }

But let's go to the 100% complete code:

public class Console {
  int[][] M; //El array.
  int X;     //Representa el eje X dentro de la matriz.
  int Y;     //Representa el eje Y dentro de la matriz.
  int C = 2; //Llevara la cuenta de los valores pares.
  int rows;  //Filas que se auto-generaran (random).
  int cols;  //Columnas que se auto-generaran (random).
  public static void main(String[] args) {
    new Console().fill();
  }

  private void fill() {
    rows = 1+new java.util.Random().nextInt(7);
    cols = 1+new java.util.Random().nextInt(7);
    System.out.printf("Rows: %d, Cols: %d%n",rows,cols);
    M = new int[rows][cols];
    X = -1;//Comienza por fuera de la dimension.
    Y = cols > 1 ? cols-2 : 0;//Depende si hay solo una o mas columnas.

    for(int k=0; k<rows*cols; k++) {
      X++;//Una linea abajo en la matriz.
      Y++;//Una columna a la derecha en la matriz.

      //Verificar si estamos por fuera de las dimensiones de la matriz.
      if(X==rows && Y==cols) {
        tracking();
      } else if(Y==cols) {
        tracking();
      } else if(X==rows) {
        tracking();
      }

      M[X][Y]=C;//Aplica al 2D Array el valor par.
      C+=2;
    }

    //Imprime en la Sout el resultado.
    for(int i=0; i<rows; i++) {
      for(int j=0; j<cols; j++) {
        System.out.print(M[i][j]+"\t");
      }
      System.out.printf("%n");
    }
  }

  //Busca, corrige y reposiciona los ejes X e Y en la matriz.
  private void tracking() {
    X=0;
    Y = cols > 1 ? cols-2 : 0;
    while(M[X][Y]!=0) {
      Y--;
      if(Y==-1) {
        X++;
        Y=0;
      }
    }
  }
}

I share the results generated randomly by this program:

    
answered by 24.11.2018 в 07:14