Monday, October 18, 2010

Arrays tip : Ignoring the zeroth row

This trick can be used in any language but is shown in java right now.
Sometimes you want to use natural input values as an index, the real values that that data has instead of starting with zero. Let's take the case of data that starts with the value 1, like the day of the month. The standard approach is to subtract one from every day value that's used as an index. This is annoying and error prone. Another way to do handle this case is to declare the array with an extra element, eg, 32 if dealing with the days in the month, then ignoring the zeroth element. If you're dealing with a two dimensional array, for example the accidents array from the previous page, you can even deallocate the first row so there won't be any possibility of referencing the zeroth day. For example,

static final int DAYS  = 32;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];
accidents[0] = null;
Because two-dimensional arrays are stored by row, you can do this. You can use the trick of allocating more columns to use the natural data, but you can't deallocate a column.
Enhanced by Zemanta

Reactions:

0 comments:

Post a Comment