Abhishek Dey
Abhishek Dey

Reputation: 1639

Finding node position in a 2D array

Can anyone help me with a solution to this problem:

There's a 2D array where each cell contains it's placeholder meaning (0,0) contain 0 (0,1) contain 1 and so on...So if we give the place holder then how can we calculate the row and column. Example: Take a 4X4 matrix. So, the config is:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Now, take 10 for example..It is (2,2)th position. So, how can we determine this? I already have an algo where I subtract 2*4 from 10(as 4 is size of array) and 2 gives me the row and 2 gives me column. So, its like :

column=given node -(row*n), where n is size of nXn array, row is 0,1,2,..

But I need a better algo. At least time complexity should be lower. Suggestions please programmers.

p.S: I came up across this while designing a solution to Monte Carlo Simulation.

Upvotes: 0

Views: 896

Answers (4)

amit
amit

Reputation: 178441

row = node / n (integer division, for example 9/4 = 2)
column = node % n (modolus operator)

The above refers to a n*n matrix, for the general case of a matrix with n rows and m columns:

row = node / m
column = node % m

Upvotes: 2

Jlennon321
Jlennon321

Reputation: 228

To determine the 2D coordinates of an element in a list you should use the following (ROW represents the row size):

int r = index / ROW;
int c = index % ROW;

For example: 10 / 4 = 2, 10 % 4 = 2

Hope this helps!

Upvotes: 0

Inbl
Inbl

Reputation: 660

(Num / 4 , Num % 4) Might be what you're looking for?

Edit: Where 4 is the number of rows or columns, in this case both are 4.

Upvotes: 0

OopsUser
OopsUser

Reputation: 4784

If your matrix row width is RowWidth Then :

row=floor(x/RowWidth)
col=x % RowWidth

Upvotes: 0

Related Questions