When I have an array (of 1D, 2D, 3D, or more dimensions), I would like to be able to translate an index (from this flatten array) into its coordinates.
For instance, considering * square:
3D array (of [2,3,2] shape)
arr = [ [ [ nil, nil ],
[ nil, nil ],
[ nil, nil ] ],
[ [ "*", nil ],
[ nil, nil ],
[ nil, nil ] ] ]
arr.flatten[6] # => "*"
arr.index2coordinates(6) # => [1,0,0] or [1][0][0]
4D array (of [2,3,1,2] shape)
arr = [ [ [ [ nil, nil ],
[ nil, "*" ],
[ nil, nil ] ] ],
[ [ [ nil, nil ],
[ nil, nil ],
[ nil, nil ] ] ] ]
arr.flatten[3] # => "*"
arr.index2coordinates(3) # => [0,0,1,1] or [0][0][1][1]
1D array (of [5] shape)
arr = [ nil, nil, nil, "*", nil ]
arr.flatten[3] # => "*"
arr.index2coordinates(3) # => [3]
How can we do a such Array#index2coordinates method? In a sense, this question is the inverse of Convert vector to integer question. Thanks a lot.
Examples, step by step:
Simple code for second example