tags:

views:

104

answers:

4

For example, given a matrix:

    01|02|03|04|05
    06|07|08|09|10
    11|12|13|14|15

And knowing that the matrix is 5x3, is there a way that if given the value '7', that we can know it is in row 2? The case is that the matrix is always ordered from 1 to n, starting from 0.

Lastly, the matrix is stored linearly in a zero based array.

A: 
Let X be your index
-------------------
column = X % width
row    = ceiling(X / width)

Edit: Seems to work now that I made some changes.

Joe Philllips
A: 

If the matrix is stored in a row-major order, then the row indices map to the element index as follows:

 rowIndex = (elementIndex - 1) / numcolumns
 columnIndex = (elementIndex % numcolumns) - 1

This is always integer division -- so no remainders. You will get the row and column indices as starting from 0.

It is left as an exercise to figure out what happens in column-major layout.

dirkgently
But 7 - 1 / 4 is 1.5, leaving 1, and in a 3x4 matrix, 7 is in the 3rd row, or index 2 in a zero based array. Unless I'm missing something your answer is not right?
ApplePieIsGood
Thanks! Fixed typo. Please see updated post.
dirkgently
In your case, numcolumns = 5. So, rowIndex = (7 - 1) / 5 = 6 / 5 = 1 (since indices start at 0, this indicates the second row). Also, columnIndex = 7 % 5 - 1 = 2 - 1 = 1 (the second column).
dirkgently
+3  A: 
row = ceiling(7 / 5)  or   ceiling(position / width)
rvarcher
Why was this modded down? Is it not correct? It seems correct and to the point.
ApplePieIsGood
I didn't downmod it... but I would point out that while this is the correct answer for a math class, it isn't an ideal *programming* solution because you'd need to do unnecessary floating point math. Also, if position and width are integers, a naive implementation of ceil(pos/width) would actually be equivalent ceil(floor(pos/width))=floor(pos/width). This depends on programming language of course, some will use floating point math for all division unless you go out of your way.
Kip
+4  A: 

if it is 0-based:

row: n / width
col: n % width

In your example, you say it is zero-based, but it is actually starting at 1, and you count the top-left element as (row,col)=(1,1), so you'd need to adjust the math:

row: (n-1) / width + 1
col: (n-1) % width + 1

In your case, n=7, width= 5:

row = (7-1)/5 + 1 = 1+1 = 2
col = (7-1)%5 + 1 = 1+1 = 2

Note: I'm using standard programmer's integer math, where "a/b" really means "floor(a/b)".

Kip
Bad communication on my part, I meant it is stored in a zero based array, not that the first value is zero based.
ApplePieIsGood