2D Arrays

Objectives

File: Array2D.java

Question 1 - Accessing 2D elements

Method print is already provided for you to demonstrate how to access 2D arrays.

Complete isIdentityMatrix method. A identity matrix or unit matrix of size n is the n-by-n square matrix with ones on the main diagonal and zeros elsewhere. The input to the method should be an 2D integer array and the method should return true if it indeed an identityMatrix.

Some examples of identityMatrix are as follows:

1 0 0           1 0 0 0 
0 1 0 0 1 0 0
0 0 1 0 0 1 0
0 0 0 1

Sample Interactions:

> int [][]data1 = {{1,0,0},{0,1,0},{0,1,5}};
> data1[2][2]
5
> Array2D.print(data1)
1	0	0	
0	1	0	
0	1	5
> Array2D.isIdentityMatrix(data1)
false
> int [][]data2 = {{1,0},{0,1}};
> Array2D.print(data2)
1	0	
0 1 > Array2D.isIdentityMatrix(data2) true

Question 2 - To demonstrate that 2D array is represented as an array of arrays

In Java, a 2D(or higher dimensional) array is represented as an array of arrays (or an array of arrays of arrays of ... and so on). Because of this, 2D arrays in Java do not need to be rectangular, like the matrices you may have seen in math class. The contents of each row is simply another array, and the lengths of these need not agree. In this case, the array is called a ragged array.

> int [][] data3 = new int[][]{{1,1}, {2,2,2},{3,3,3,3}}; //ragged array
> Array2D.print(data3)
1	1	
2 2 2
3 3 3 3 > data3.length //# of rows 3 > data3[0].length //# of cols for row 0 2 > data3[1].length 3 > data3[2].length 4 > data3[0] = data[1]; > Array2D.print(data3) 2 2 2
2 2 2
3 3 3 3

Complete the method growCols which increase the number of columns in row i to be at least newSize

> int [][] data3 = new int[][]{{1,1},{2,2,2},{3,3,3,3}};
> data3[0][2]
ArrayIndexOutOfBoundsException:
> Array2D.growCols(data3, 0, 3); //increase row # 0's size to 3
> data3[0][2] 
0                                
> Array2D.print(data3)  
1	1	0	
2 2 2
3 3 3 3

Make sure to devise your own tests.