C# – Most elegant way to get the array element by position

.netarraysc++

I have an array:

private int[,] _blocks = new int[6, 4];

It represents a set of blocks which is 6 deep horizontally and 4 deep vertically. Graphically it looks like this:

alt text http://www.angryhacker.com/toys/array.png

I need a function that would take in a number, from 1 to 24 and return the array element that matches. So for number 14, I'd get back _blocks[1, 2];

I've created a simplistic function:

private int GetBlockByPosition(int position)
{
    int count = 0;
    for (int i = 0; i < 6; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (++count == position)
                return _blocks[i, j];
        }
    }
    return -1;
}    

But this seems very wasteful and smells bad. Is there a more elegant and faster way?

Best Solution

Both in the horizontal direction and the vertical direction, you can see a pattern in your table of numbers. You can determine the horizontal position with position / 6 and a vertical position with position % 6 -- the modulo operation.

private int GetBlockByPosition(int position)
{
    return _blocks[((position + 6) / 6) - 1, position % 6];
}

This makes mathematical sense. Division increases in chunks, and modulo (remainder on division) increases one by one. The math is pretty simple.