3d grid cell calculation

835 Views Asked by At

i am not sure if i selected correct category for my question. Lets say i have a 2d grid. Every cell in the grid has an id which is calculated using formula: currentRow * totalColumns + currentColumn + 1. So if you have a grid with 5 rows and 4 columns and cell with x,y coordinates: 3, 0 its id is 13.

Now in reverse if i want to find x,y coordinates based only on cell Id and total row and columns i will do this:

row = (id - 1) / totalColumns
column = (id - 1) % totalColumns

What i want is to add a third dimension (which will make the grid a cube), lets name it slices. So i now calculate the cellid using the formula:

currentRow * totalColumns + currentColumn + currentSlice + 1

But i cant find out how to do the reverse operation, how to find the x,y,z coordinates based on cellid and total rows columns and slices.

1

There are 1 best solutions below

1
On BEST ANSWER

The problem with your new formula is that it is maping different cells to the same id. You need something a bit more complex than that.

You can try

currentSlice * totalRows * totalColumns + currentRow * totalColumns + currentColumn + 1

You can show this function now maps every cell to a unique id.

To get your coordinates back you do something similar:

column = (id - 1) % totalColumns
row = ((id - column - 1)/totalColumns) % totalRows
slice = (((id - column - 1)/totalColumns)-row) / totalRows

This can be generalized to a $n $-dimensional table.