Pergunta de entrevista da empresa Ooyala

diagonally print a matrix

Respostas da entrevista

Sigiloso

12 de jun. de 2012

public static void printDiagonal (int [][] M) { int rows = M.length; int columns = M[0].length; int numDiags = rows + columns -1; int rowIndex = 0; int columnIndex = 0; for (int i=0; i =0 && row < rows; row++, col-- ) { System.out.print (M[row] [col] + " "); } System.out.println(); } }

1

Sigiloso

3 de mar. de 2014

Good. A non-optimal answer would be just making the check before printing: public static void diagonallyPrintMatrix ( int [][] m ) throws Exception { if ( m == null || m.length == 0 || m [ 0 ].length == 0 ) throw new Exception ( "Wrong input" ); int height = m.length; int width = m[0].length; for ( int i = 0; i < width + height - 1; i++ ){ int x = i; int y = 0; for ( int j = 0; j < i + 1; j++ ){ if ( 0 <= x && x < height && 0 <= y && y < width ) System.out.print ( m [ x ][ y ] + " "); x--; y++; } System.out.println (""); } }

Glassdoor | Glassdoor