2011-01-21 29 views
1

我試圖想出一個方程式,以數學方式確定「堆疊索引」數組的「平坦索引」。在Ruby中觀察下面的例子。從「堆疊索引」中找出「平坦索引」

matx = [[[ 1, 2, 3, 4], 
     [ 5, 6, 7, 8]], 

     [[ 9,10,11,12], 
     [13,14,15,16]]] 

在這個例子中,是matx三維基質,並且元件7位於matx[0][1][2]。然而,在下面的例子中:

matx.flatten! # => [1, 2, 3, 4, 5, 6, 7, 8, 
       #  9, 10, 11, 12, 13, 14, 15, 16] 

現在元件7位於matx[6]

所以基本上,我正在尋找一種方法,給定矩陣的大小和特定元素的索引集,從堆棧矩陣轉換爲平坦矩陣。 反向也是很棒的,但我想到了獲得這種結果的方法類似(但基本上顛倒)的方法。 我意識到reverse實際上並不是一個函數,因爲沒有辦法一定要區分是否映射到[2,3]或[3,2]等等。所以我不打算查看一。

回答

2
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 
+0

這很好。唯一困惑的兩件事情是 a)你爲什麼要改變它?和 b)注射實際上在做什麼? – ashays 2011-01-22 00:12:08