Find out "flattened index" from "stacked index" of an Array
I'm trying to come up with an equation to mathematically determine the "flattened index" of an array from the "stacked index." Observe the following example in Ruby.
matx = [[[ 1, 2, 3, 4],
[ 5, 6, 7, 8]],
[[ 9,10,11,12],
[13,14,15,16]]]
In this example, matx
is a three dimensional matrix, and the element 7
is located at matx[0][1][2]
. However, in the next example:
matx.flatten! # => [1, 2, 3, 4, 5, 开发者_JS百科6, 7, 8,
# 9, 10, 11, 12, 13, 14, 15, 16]
Now the element 7
is located at matx[6]
.
So essentially, I'm looking for a way to, given the dimensions of the matrix and the set of indices for the particular element, convert from the stacked matrix to the flattened matrix. Reverse would be awesome, too, but I figure the way to get that is similar (but essentially reversed) to the method of obtaining this result. I realized that reverse is not actually a function, because there's no way to necessarily tell the difference as to whether 5 maps to [2,3] or [3,2], etc. So I'm not going to look into that one.
class Index
def initialize *dims
@dims = dims.reverse
end
def if_flat *subs
raise unless @dims && @dims.size == subs.size
res = 0
subs.reverse.each_with_index { |s, i| res += s * @dims[0...i].inject(1) { |m, e| m * e }}
res
end
end
puts Index.new(2, 2, 4).if_flat 0, 1, 2
精彩评论