Showing posts with label array/2DArray. Show all posts
Showing posts with label array/2DArray. Show all posts

Tuesday, 17 May 2011

Visualizing 2D arrays : How java implements multidimensional arrays ?

A two dimensional array is implemented as an array of one dimensional arrays. This is called "array of arrays" approach.

2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an array, a, with two rows and four columns.

int[][] a = new int[2][4];  // Two rows and four columns.


















a[0][0]a[0][1]a[0][2]a[0][3]
a[1][0]a[1][1]a[1][2]a[1][3]
Two-dimensional arrays are usually visualized as a matrix, with rows and columns. This diagram shows the array a with its corresponding subscripts.

This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual row arrays, and a two one-dimensional arrays of 4 elements to represent the contents of the rows.


Common approach to implement multidimensional arrays


There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Some languages, like Java, build multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. C++ supports both styles.

Common usage of ragged arrays

One consequence of arrays of arrays is that each row can be a different size, called ragged or non-uniform arrays.

One usage of ragged arrays is triangular arrays. For example, we could create a lower triangular array, allocating each row "by hand" as follows. Note how new can be used with only the row dimension.

int[][] tri;

//... Allocate each part of the two-dimensional array individually.
tri = new int[10][]; // Allocate array of rows
for (int r=0; r < tri.length; r++) {
tri[r] = new int[r+1]; // Allocate a row
}


A good example of a triangular array is one of those tables of the distance between two cities that is often in the front of some road atlas covers. The distance from New Delhi to Agra is the same as the distance from Agra to New Delhi- there's not need to have it twice in the same table - at least if you have a need for that remaining space.

Naming convention : Use named constants for array sizes

It's useful to define constants for the number of rows and columns. The reason named constants can better code is that these numbers may represent part of the problem domain and they will be used in other parts of the code. If a change is every necessary (eg, the number of teams in the Big Ten), changing one named constant will change all parts of the program. Each numeric "constant" should only appear once (the "DRY" principle).

static final int ROWS = 2;
static final int COLS = 3;
. . .
int[][] board = new int[ROWS][COLS];

Many row and column indexes (indices is the traditional English plural, but many prefer the more modern indexes) have a meaning, and aren't just simply arbitrary numbers. The following example might be used to represent the number of accidents on by day of the month and the hour of the day. See programming problems below for some examples using this array.
static final int DAYS  = 31;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];

Multi-dimensional arrays in java

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common. Higher dimensional arrays are less common so they aren't used in the examples, but there's nothing mysterious about them and the same principles apply.
Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the idea, altho not the implementation, of graphics that specifies a two (or three) dimensional position with an x and y (and z) coordinate.
Terminology. Other terms you will see for a two-dimensional array are matrix or table.

Monday, 25 October 2010

2D Array Declaration, Allocation and Initialization

Introduction

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common. Higher dimensional arrays are less common so they aren't used in the examples, but there's nothing mysterious about them and the same principles apply.
Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the idea, altho not the implementation, of graphics that specifies a two (or three) dimensional position with an x and y (and z) coordinate.
Terminology. Other terms you will see for a two-dimensional array are matrix or table.

Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach.

Declaration

Two-dimensional arrays are objects. A variable such as gradeTable is a reference to a 2D array object. The declaration

int[][] myArray ;

says that myArray is expected to hold a reference to a 2D array of int. Without any further initialization, 
it starts out holding null.


Allocation


The declaration
int[][] myArray = new int[3][5] ;

says that myArray can hold a reference to a 2D array of int, creates an array object of 3 rows and 5 columns, and puts the reference in myArray. All the cells of the array are initialized to zero. The declaration


int[][] myArray = { 
{0,0,0,0,0}, 
{0,0,0,0,0}, 
{0,0,0,0,0} 
};



does exactly the same thing as the previous declaration (and would not ordinarily be used.)

Initialization


The declaration


int[][] myArray = { 
{8,1,2,2,9}, 
{1,9,4,0,3}, 
{0,3,0,0,7} 
};


creates an array of the same dimensions (same number of rows and columns) as the previous array and initializes the cells to specific values.


Length of 2D array

The length of a 2D array is the number of rows it has. You might guess that "length" could be defined as a number pair (rows, columns). But the number of columns may vary from row to row so this will not work.

eg.
        int arr[][] = new int[2][4];
so arr.length = 2, and arr[0].length=4 i.e. length of row.


(Note we are using length and not length() )
Using .length instead of named constants in 2D arrays(unlike c/cpp)

Named constants make a program very readable, but they may not be available if the array has been passed as a parameter. You can get the size of each dimension with the .length attribute. This is the most general style.
for (int row = 0; row < a2.length; row++) {
       for (int col = 0; col < a2[row].length; col++) {
           output += " " + a2[row][col];
       }
       output += "\n";
} 



Iterating over 2 Dimensional Arrays

Iterating down rows, then across columns is often better. The most common practice is for the outer loop be for the row and the inner loop for the column. If your program requires the outer iteration by columns, that's fine, but the default row-first iteration gives the best performance because "locality of reference" improves the perfomance of cache and virtual memory. It also allows use of the handy foreach loop.

int[][] a2 = new int[ROWS][COLS];

String output = "";   // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) {
    for (int col = 0; col < COLS; col++) {
        output += " " + a2[row][col];
    }
    output += "\n";
}


foreach style for loop


for (int[] row : a2) {
            for (int val : row) {
                output += " " + val;
            }
            output += "\n";
        }
  

Types of 2D arrays in java


2D arrays in java are of 2 types – even and ragged or uneven arrays.
Defining an even array
Here, Each row of a 2D array may have a same number of cells in the array.

int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];


Defining non-uniform or ragged arrays

Here, each row of a 2D array may have a different number of cells.


int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4]; 


Similarly we can initialized ragged arrays like :

int[][] uneven = 
    { { 1, 9, 4 },
      { 0, 2},
      { 0, 1, 2, 3, 4 } };

Assigning 1D array to row of 2D array

int myArray[][] = new int [4][4];
myArray[0] = new int[] {1, 9, 4,7,8} ;   
int[] x = {1, 7, 4,5,6,7,6,90,4,5,6,7,8,9,0,1,3,4,5} ; // declare and init x
myArray[1]=x;