Popular Posts

Monday, October 03, 2011

Java: Triangular Array (varying sized rows array)


Can we achieve varied-size rows in a two dimensional array in Java language like in PHP and other languages?

Absolutely!
When a double dimensional array is instantiated like this
int[][] array = new int[n][m] 

then all rows are of the same size m

Consider for example int[][] array = new int[10][5]
All rows in this double dimensional array would be of equal size 5.

But this is not what we need...we wanted varying-size rows in double dimensional array, right?

Here is the technique to produce varying-size row.
int[][] array = new int[10][];  

Don't instantiate the column part of the array in order to be able to get varied size columns of the array later on.

like this...
array[0] = new int[1]; //row0 of size 1
array[1] = new int[2]; //row1 of size 2
array[2] = new int[3]; //row2 of size 3
.....

Take a look at below code which produces Triangular array


 0
 0 0
 0 0 0
 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0


public static void TriangularArray(int maxRow){
		
		int[][] triangle;

		// instantiating only row part of the array (total number of rows)
		triangle = new int[maxRow][];
		
		// Now instantiate individual columns separately with different sizes and assign them to rows  
		for (int r=0; r < triangle.length; r++) {
		    triangle[r] = new int[r+1]; 
		}

		// Print the triangular array
		for (int r=0; r<triangle.length; r++) {
		    for (int c=0; c<triangle[r].length; c++) {
		        System.out.print(" " + triangle[r][c]);
		    }
		    System.out.println("");
		}
	}