Search code examples
arraysmatrixmodulo

Accessing the nth element of a matrix


Given a number n and a matrix, represented as an array of arrays, how would you find the nth element? The answer I am looking should involve the modulus operation and not use standard library functions.

So, for example, when n = 7 and the matrix is:

[
[a_1,a_2,a_3,a_4],
[a_5,a_6,a_7,a_8],
[a_9,a_10,a_11,a_12]
]

I want to access a_7.

Since my array is a matrix, all rows are always of the same length.


Solution

  • Suppose we use zero-based indexing to make things simpler. So, if we want the 7th element, we use n=6.

    rowIndex = n / rowLength
    columnIndex = n % rowLength
    answer = array[rowIndex][columnIndex]