Index to coordinates conversion, according the matrix shape

Hello,

I would like to converte an index (of a flatten array) to a
multi-dimensions coordinates (of the multi-dimensions version of the
previous flatten array).

Example:

Considering the following 2 dimensions array (3x3):

[ [ -, -, - ],
  [ *, -, - ],
  [ -, -, - ] ]

We can see that, the coordinates of the checked case is [0, 1].

Now, if we flat this array, it looks like:

[ -, -, -, *, -, -, -, -, - ]

Here, we can see the coordinate (or the index) of the checked case is 3.

But how can we do the opposite? I mean, a method looking like:

index_to_coordinates([3, 3], 3) # => [0, 1]

Thanks!

This is a perfect case for modulo (%). It gives the remainder of a
division.

 def index_to_coordinates arr_size, index
   x = index % arr_size[0]
   y = (index - x) / arr_size[0]
   return x, y
 end

 coordinates [3, 3], 3 # => [0, 1]

You will notice that the “matrix height” (arr_size[1]) is not used for
the calculation. However, you might want to check that the index you ask
is not out of bounds.

PS: I usually make some stupid mistakes when doing math, so the code
above may be incorrect. However, the basic idea is here: modulo.

Hashmal wrote in post #997453:

This is a perfect case for modulo (%). It gives the remainder of a
division.

 def index_to_coordinates arr_size, index
   x = index % arr_size[0]
   y = (index - x) / arr_size[0]
   return x, y
 end

 coordinates [3, 3], 3 # => [0, 1]

Waw, thanks. But… is this okay with matrix of more then 2 dimensions?
:slight_smile:

Such as this one:

NArray.object(2,3,2):
[ [ [ nil, nil ],
[ nil, nil ],
[ nil, nil ] ],
[ [ nil, nil ],
[ nil, nil ],
[ nil, nil ] ] ]

Le 9 mai 2011

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs