Wednesday, May 18, 2011

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.

No comments:

Post a Comment

Chitika