Lets say I have an original mxn matrix like this:
1 2 3 4
5 6 7 8
For the purpose of my program, I then concatenate the rows into this new one dimensional matrix:
1 2 3 4 5 6 7 8
I know the mxn size of the original matrix. My question is, given a value's position in the new matrix, I need an algorithm to find its mxn position in the original matrix.
For example: Using the above matrices, 8 would have an original position of 2x4, 3 would have an original position of 1x3 and so on.
This is for a java program that I am writing, I tried using division and modulus and played around with it, but I couldn't come up with a good algorithm that works for all cases.
1 Answer 1
If A is the original two-dimensional matrix, B is the new one-dimensional matrix, m & n are height and width of B respectively, then given the position p of element a in A, the new [x,y]
coordinates within B (given indices that are one-based) is
x = (p - 1) / n + 1
y = n + 1 - (p % n)
With zero-based indices, this becomes easier, as you no longer have to adjust for the 1 offset.
x = p / n
y = n - p % n
-
Thank you! I'm working with 0 based but the end value has to be 1 based for the user.gptt916– gptt9162016年05月18日 03:38:17 +00:00Commented May 18, 2016 at 3:38
-
I just sat down to finish up my code, I think there may be some confusion, I need the [x,y] coordinates within A(mxn) given position p of element in B (one dimensional)gptt916– gptt9162016年05月18日 04:04:59 +00:00Commented May 18, 2016 at 4:04