MULTI-DIMENSIONAL ARRAYS

CONTENTS

1. Overview
2. Simple example
3. Unconstrained (dynamic) multi-dimensional arrays
4. A more complex 2-D array example --- finding the determinant of a 3x3 matrix.
5. Non-Rectangular arrays (arrays of arrays).


1. OVERVIEW

Multi-dimensional arrays are arrays where the elements have more than one index. In the case of two-dimensional arrays these can be envisaged as tables comprising a number of rows and column such that the row number represents one index and the column number a second index:

12
34
56

Three dimensional arrays can then be envisaged as comprising a book of tables (Figure 1) such that the third index represents page number. Four dimensional arrays can then be envisaged as a set of books of tables, five dimensional arrays as a number of filing cabinet draws each containing a set of books, and so on.

THREE-DIMENSIONAL ARRAY CONCEPTUALISATION

Figure 1: 3D array conceptualisation

FIVE-DIMENSIONAL ARRAY CONCEPTUALISATION

Figure 2: 5D array conceptualisation!



2. SIMPLE EXAMPLE

Consider the code given below

// 2-D ARRAY EXAMPLE
// Frans Coenen
// 11 February 2000
// Dept Computer Science, University of Liverpool


class Array2Dexample{

    public static void main(String[] args) /* throws IOException */ {
    	int[][] my2Darray = {{1,3,5},{2,4,6}};
	
	System.out.println("Row size (number of elements in row)         = " + my2Darray.length);
	System.out.println("Column size (number of elements in a column) = " + my2Darray[0].length);
	
	outputArray(my2Darray);
	}

    /* OUTPUT ARRAY */
    
    public static void outputArray(int[][] array) {
	int rowSize = array.length;
	int columnSize = array[0].length;
	
    	for(int index2 = 0; index2 < columnSize;index2++) {
	    System.out.print("(");
	    for(int index1 = 0; index1 < rowSize;index1++) {
	        System.out.print(" " + array[index1][index2]);
		}  
	    System.out.println(" )");
	    }	
	System.out.println();
        }	
    }

Table 1: 2-D array example



3. UNCONSTRAINED (DYNAMIC) MULTI-DIMENSIONAL ARRAYS

As with ordinary one-dimensional arrays, multi-dimensional arrays can also be unconstrained. An example of this appraoch is given in Table 2 where the user is given the opportunity of specifying the domensions of a 2-D array.

// 2-D ARRAY EXAMPLE
// Frans Coenen
// 11 February 2000
// Dept Computer Science, University of Liverpool

import java.io.*;

class Array2Dexample{

    // ------------------- FIELDS ------------------------ 
                               
    public static int numberOfRows;
    public static int numberOfColumns;
    public static int myArray[][];
    public static InputStreamReader input      = new InputStreamReader(System.in);
    public static BufferedReader keyboardInput = new BufferedReader(input);
    
    // ------------------ METHODS ------------------------
                               
    public static void main(String[] args) throws IOException {
    	
	inputArray();
	outputArray();
	}

    /* INPUT ARRAY */
     
    public static void inputArray() throws IOException {
    
        // Input array size
	
    	System.out.print("Input number of rows ");
	numberOfRows = new Integer(keyboardInput.readLine()).intValue(); 
        System.out.print("Input number of columns ");
	numberOfColumns = new Integer(keyboardInput.readLine()).intValue();
        
	// Declare size of 2D array
	
	myArray = new int[numberOfRows][numberOfColumns];
	
	// Load array
	
	for(int index2 = 0; index2 < numberOfColumns;index2++) {
	    for(int index1 = 0; index1 < numberOfRows;index1++) {
		System.out.print("Input (integer) element [" + index1 + "][" +
				index2 + "] ");
		myArray[index1][index2] = new Integer(keyboardInput.readLine()).intValue(); 
		}
	    }	
	System.out.println();
        }
	
    /* OUTPUT ARRAY */
    
    public static void outputArray() {
	
    	for(int index2 = 0; index2 < numberOfColumns;index2++) {
	    System.out.print("(");
	    for(int index1 = 0; index1 < numberOfRows;index1++) {
	        System.out.print(" " + myArray[index1][index2]);
		}  
	    System.out.println(" )");
	    }	
	System.out.println();
        }	
    }

Table 2: 2-D unconstrained array example



4. MORE COMPLEX 2-D ARAY EXAMPLE --- `DETERMINANT' OF A 3x3 MATRIX

The determinamt of a 2x2 matrix is the product of the elements of the leading diagonal minus the other diagonal product. Thus if:

A = ( a b )
    ( c d )

We can write a trivial method to retrun the determinant of a 2x2 array as follows:

public int determinant2x2(int[2][2] matrix) {
    return((matrix[0][0]*matrix[1][1])-(matric[0][1]-matrix[1][0]));
    }      

The determinant of a matrix A is denoted by |A| or (in the case of the above example):

| a b |
| c d |

The determinant of a 3x3 matrix A (|A) is found as follows:

                       ( a1 a2 a3 )
                   A = ( b1 b2 b3 )
                       ( c1 c2 c3 )
		       
|A| = a1 | b2 b3 | - a2 | b1 b3 | + a3 | b1 b2 |
         | c2 c3 |      | c1 c3 |      | c1 c2 |

We can encode this in a geneeral matrix class as shown in Table 3. Note that the determinant method will work for any square matrix.

// MATRIX CLASS
// Frans Coenen
// 11 February 2000
// Dept Computer Science, University of Liverpool

import java.io.*;

class Matrix {

    // ------------------- FIELDS ------------------------ 
                               
    private int numberOfRows;
    private int numberOfColumns;
    private int matrix[][];
    
    // ------------------ METHODS ------------------------
    
    /* INPUT ARRAY */
     
    public void inputArray() throws IOException {
        InputStreamReader input      = new InputStreamReader(System.in);
        BufferedReader keyboardInput = new BufferedReader(input);
    
        // Input array size
	
    	System.out.print("Input number of rows ");
	numberOfRows = new Integer(keyboardInput.readLine()).intValue(); 
        System.out.print("Input number of columns ");
	numberOfColumns = new Integer(keyboardInput.readLine()).intValue();
        
	// Declare size of 2D array
	
	matrix = new int[numberOfRows][numberOfColumns];
	
	// Load array
	
	for(int index2 = 0; index2 < numberOfColumns;index2++) {
	    for(int index1 = 0; index1 < numberOfRows;index1++) {
		System.out.print("Input (integer) element [" + index1 + "][" +
				index2 + "] ");
		matrix[index1][index2] = new Integer(keyboardInput.readLine()).intValue(); 
		}
	    }	
	System.out.println();
        }
    
    /* INPUT COLUMN */
    
    private void inputColumn(int[][] newMatrix, int[][] oldMatrix, int newColIndex, int oldColIndex) {
        int rowIndex;
	
        for(rowIndex=1;rowIndex < oldMatrix[0].length;rowIndex++) {
	    newMatrix[newColIndex][rowIndex-1] = oldMatrix[oldColIndex][rowIndex];
	    }
        }
		
    /* OUTPUT ARRAY */
    
    public void outputArray() {
	
    	for(int index2 = 0; index2 < numberOfColumns;index2++) {
	    System.out.print("(");
	    for(int index1 = 0; index1 < numberOfRows;index1++) {
	        System.out.print(" " + matrix[index1][index2]);
		}  
	    System.out.println(" )");
	    }	
	System.out.println();
        }
    
    /* DETERMINANT */
    
    public int determinant() {
	if (numberOfColumns != numberOfRows) {
	    System.out.println("ERROR: can only find determinant of a square matrix");
	    return(0);
	    }
	else {
	    if (numberOfColumns != 1) return(determinant(matrix));
	    else {
	        System.out.println("ERROR: can not find determinant of a one element matrix");
	        return(0);
		}
	    }
	}
	
    private int determinant(int[][] oldMatrix) {
        int length = oldMatrix.length;
	int colIndex;
	
	// If 2x2 return determinant
	
	if (length == 2) return(oldMatrix[0][0]*oldMatrix[1][1] - 
		    	oldMatrix[0][1]*oldMatrix[1][0]);
	else {
	    int determinant=0;
	    for (int index=0;index < oldMatrix.length;index++) {
	    	int[][] newMatrix = new int[length-1][length-1];
		for(colIndex=0;colIndex < index;colIndex++) {
		    this.inputColumn(newMatrix,oldMatrix,colIndex,colIndex);
		    }	
		for(colIndex=index+1;colIndex < oldMatrix.length;colIndex++) {
		    this.inputColumn(newMatrix,oldMatrix,colIndex-1,colIndex);
		    }
		if (index%2 == 0) determinant = determinant + determinant(newMatrix);
		else determinant = determinant - determinant(newMatrix);
		}
	    return(determinant);
	    }	    
        } 
    }

Table 3: Matrix class

The code presented in Table 3 of course needs an application class to go with it --- this is presented in Table 4. Some sample output, generated using tghis code, is given in Table 5.

// MATRIX APPLICATION
// Frans Coenen
// 11 February 2000
// Dept Computer Science, University of Liverpool

import java.io.*;
import Matrix;

class MatrixApp {

    // ------------------ METHODS ------------------------
                               
    public static void main(String[] args) throws IOException {
        
	Matrix newMatrix = new Matrix();
	
        newMatrix.inputArray();
	newMatrix.outputArray();
	System.out.println("Determinant = " + newMatrix.determinant());
        }
    }

Table 4: Application class for code presented in Table 3

$ java MatrixApp
Input number of rows 3
Input number of columns 3
Input (integer) element [0][0] 0
Input (integer) element [1][0] 1
Input (integer) element [2][0] 2
Input (integer) element [0][1] 3
Input (integer) element [1][1] 4
Input (integer) element [2][1] 5
Input (integer) element [0][2] 6
Input (integer) element [1][2] 7
Input (integer) element [2][2] 8

( 0 1 2 )
( 3 4 5 )
( 6 7 8 )

Determinant = 0             

Table 5: Sample output



5. NON-RECTANGULAR ARRAYS (ARRAYS OF ARRAYS)

All the 2-D array examples we have looked at so far have assumed the arrays we are interested in are "rectangular". However, multi diemsnioanl arrays are represented (in Java) as arrays of arrays, i.e. arrays of elements who are them selves arrays. Consequently 2-D arrays do not have to be rectangular. For example we can may define a "triangular" array thus:

int[][] triangle = {{1,1},{1,2,1},[1,3,3,1},{1,4,6,4,1}}

(Pascal's triangle).

Alternatively we can conseive of a fixed length array whose elements are arrays of varying length. The code in Table 6 produces such an array in a random manner (some sample output is given in Table 7).

// TWO DIMENSIONAL DYNAMIC ARRAY EXAMPLE
// Frans Coenen
// Friday 25 May 2000
// Depaertment of Computer Science, University of Liverpool

/* Code to create and output a two dimensional array whose "X2 dimensio
is fixed at 10 and whose "Y" dimension for each record is of some random 
length between 1 and 10 */


class TwoDdynamicArray {

/* ------------------------------- */
/*                                 */
/*              FIELDS             */
/*                                 */
/* ------------------------------- */
    
    private static final int TOTAL_ROWS = 10;
    private static int[][] myArray = new int[TOTAL_ROWS][];
     
/* -------------------------------- */
/*                                  */
/*              METHODS             */
/*                                  */
/* -------------------------------- */

    /* MAIN */
    
    public static void main(String[] args) {
        loadArray();
	outputArray();
	}
	
    /* LOAD ARRAY */
    
    static void loadArray() {
	int numCols,index2;
	
	// Nested loop
	
	for (int index1=0;index1 < TOTAL_ROWS;index1++) {
	    numCols = 1 + Math.abs((int) ((Math.random())*10.0));     
	    myArray[index1] = new int[numCols];
	    for (index2=0;index2 < numCols;index2++) 
				myArray[index1][index2] = (int) ((Math.random())*10.0);  
	    }
	}
    
    /* OUTPUT ARRAY */
    
    static void outputArray() {
        int length, index2;
	
        // Nested loop
	
        for (int index1=0;index1 < TOTAL_ROWS;index1++) {
	    length = myArray[index1].length;
	    for (index2=0;index2 < length;index2++) 
	    			System.out.print(myArray[index1][index2] + " ");  
	    System.out.println();
	    }
	
	// End
	
	System.out.println();
	}    
    }

Table 6: Array of arrays example

$ java TwoDdynamicArray
7 6 3 1 2 6 0 0 0
9 4 8 3 2 8
8 3 4 3 2 0 7 6
6 5 3 1 2 5 3
8 6 0 2 4 8 5 6 6
6 3 7 8 4 0
1 7 0 7 8 6 3 3 0
5 0 2
3
9 9 4 4 7 7 1 5 4

$ java TwoDdynamicArray
5 8 0
4 9 2
2 6 6 9 7
8 9 1 9 7 0 5 2 5 4
8 9 8 2 6 6
5 0 3 4 9 0 5
9 1 5 1 5 8 7 1 3 0
1 2 7 7 1 2
4 1 5 7 6 3 3 1 5 7
3 3 5 0 4 7 8 5 9          

Table 8: Sample output for array of arrays example

An example program which calculates Pascal's Triangle to a user specified level is presented in Table 8.

// PASCALS TRIANGLE CLASS
// Frans Coenen
// 6 March 2000
// Dept Computer Science, University of Liverpool

import java.io.*;

class PascalsTriangle {

    // ------------------- FIELDS ------------------------ 
                               
    private int numOfRows;
    private int triangle[][];
    
    // ---------------- CONSTRUCTOR ---------------------
    
    PascalsTriangle(int level) {
        triangle = new int[level][];
	}
	
    // ------------------ METHODS ------------------------
    
    /* CALCULATE ROWS */
     
    public void calculateRows() throws IOException {
        int index1 = 1, index2;
    
 	/// First level in triangle
	   
    	int [] triangleRow = {1,1};
	triangle[0] = new int [2];
	triangle[0] = triangleRow;;
	
	// Rest of levels
	
	while (index1 < triangle.length) {
	    triangleRow = new int[index1+2];
	    triangleRow[0] = 1;
	    index2=1;
	    while (index2 < =index1) {
		triangleRow[index2] = triangle[index1-1][index2-1] + triangle[index1-1][index2];
		index2++;		
		}	
            triangleRow[index2] = 1;
	    triangle[index1] = triangleRow;	
	    index1++;
	    } 
        }
	
    /* OUTPUT TRIANGLE */
    
    public void outputTriangle() {
        
	for(int index=0;index < triangle.length;index++) {
	    outputRow(triangle[index]);
	    }
	}
	
    /* OUTPUT ROW */
    
    private void outputRow(int[] row) {
        
	for(int index=0;index < row.length;index++) {
	    System.out.print(row[index] + "  ");
	    }
	
	// End
	
	System.out.println();
	}
    }

Table 8: Pascal's triangle class

An applicationms program that utilises the code presented in Table 8 is given in Table 9. Some sample output is presented in Table 10.

// PASCALS TRIANGLE APPLICATION
// Frans Coenen
// 6 MARCH 2000
// Dept Computer Science, University of Liverpool

import java.io.*;
import PascalsTriangle;

class PascalApp {
    
    private static InputStreamReader input      = new InputStreamReader(System.in);
    private static BufferedReader keyboardInput = new BufferedReader(input);
    
    // ------------------ METHODS ------------------------
                               
    public static void main(String[] args) throws IOException {
        
	// Input required level
	
	System.out.print("Input required level ");
	int level = new Integer(keyboardInput.readLine()).intValue(); 
	PascalsTriangle newPascal = new PascalsTriangle(level);
	
	// Generate triangle
	
	newPascal.calculateRows();
        
	// output
	
	newPascal.outputTriangle();
	}
    }

Table 9: Application class for code presented in Table 6

$ java PascalApp
Input required level 10
1  1
1  2  1
1  3  3  1
1  4  6  4  1
1  5  10  10  5  1
1  6  15  20  15  6  1
1  7  21  35  35  21  7  1
1  8  28  56  70  56  28  8  1
1  9  36  84  126  126  84  36  9  1
1  10  45  120  210  252  210  120  45  10  1             

Table 10: Sample output for Pascal's triangle example




Created and maintained by Frans Coenen. Last updated 10 January 2001