Friday 6 April 2012

Array Choices

In order to put some icons on our grid, we need to use an array.  This is simply a variable with more than one slot to put things in.  Arrays can be single dimension - as in a list, or multi dimensional - like in a table.

For the icons in our panel we have a couple of choices.

We could use a two dimensional array with one dimension for the row, the other for the column - as in the Green numbers in the diagram.  Or we can use a single dimensional array and calculate the position from the row and the column - as in the Red numbers.

To process the entries in the array, we could use two nested loops, one for the row and the other for the column,  or we could use one loop and calculate the row and column.

Novice programmers tend to use the two dimensional approach as this better represents how the objects are positioned, that is not to say someone who chooses this approach is a novice or in some way not as good a programmer.  Its a personal choice.

Either way some calculation will be needed since we will be dealing with the position (2 dimensional) of icons in a list (1 dimensional).

Looking at the diagram - which has five rows and five columns, you might be able to see what the calculations are.  The number five features heavily in them.
  • The red number is calculated by multiplying Y by 5 and adding X
  • Y is calculated by dividing the red number by 5 and ignoring any remainder or fraction
  • X is calculated using modula division by 5 on the red number.
Modula division uses the remainder from a normal division as its answer.

For example 13 divided by 5 is 2 remainder 3, so for red number 13, we get Y of 2 (normal division) and X of 3 (modula division)


Note that in all these calculations, the 5 comes from the number of columns.


In programming terms (with the red number using R) this is expressed as

R = Y * 5 + X

Y = R / 5
X = R mod 5

With integer variables, any fractions are discarded so the results are always integer (whole) numbers.


My personal choice is to use a one dimension array and here is why.

Suppose we have seven icons.

If we process the icons using two loops, one for X and one for Y, then for each position in the grid we would have to check if we have gone past the number of icons - in this case 7.

If we process them with one loop, we can simply count up to 7 and stop.

If we are processing them with one loop, then we may as well store them in one dimension with an index which matches the count.


With that out of the way, we can proceed.

No comments:

Post a Comment