2016-03-02 123 views
2

我具有n深度陣列,其中n是大於變量大於或等於2:紅寶石 - 陣列弄平

[[1,1],[[1,1],[1,1]]] 

我想變平該數組具有完全相同2的深度,這樣的:

[[1,1],[1,1],[1,1]] 

任何人都可以想出一個很好的方法來實現這一目標嗎?

+1

要如何輸出目前還不清楚;例如爲什麼'[[1,1],[1,1]]'變成'[1,1],[1,1]'而不是'[1,1,1,1]'? – brito

+0

更多情況下可能需要獲得任何有用的東西。但首先,你有什麼嘗試?也許[#flatten](http://ruby-doc.org/core-2.3.0/Array.html#method-i-flatten)與一個級別參數?什麼? –

回答

3

這應該這樣做。

def flatten_after_first(arr) 
    arr.flat_map { |a| a.first.is_a?(Array) ? a.map(&:flatten) : [a] } 
end 

flatten_after_first [[1,1],[[1,1],[1,1]]] 
    #=> [[1, 1], [1, 1], [1, 1]] 

flatten_after_first [[1,1], [[2,2], [2,2]], [[[3,3], [3,3]], [[3,3], [3,3]]]] 
    #=> [[1, 1], [2, 2], [2, 2], [3, 3, 3, 3], [3, 3, 3, 3]] 
+0

是的,OP通過在標題中寫入「深度優先」來拋棄所有人。他在這個問題中給出的例子不是你在深度第一次變平時得到的結果。但看起來你的答案是他想要的。 –

0

試試這個:

def depth_first_flatten array 
    result = [] 
    array.each do |element| 
    if element.first.is_a? Array 
     result += deph(element) 
    else 
     result << element 
    end 
    end 
    result 
end 

# array = [[1,2],[[3,4],[5,6]]] 
# depth_first_flatten(array) 
# 
# OUTPUT: [[1, 2], [3, 4], [5, 6]] 
+0

我也用'array = [[1,2],[[3,4],[5,6]],[[[[7,8],[9,10]]]]] ''[1,2],[3,4],[5,6],[7,8],[9,10]]' –

+0

測試'array = [[1,1],[ [1,1],[1,1],[[1,2],[1,2,3]]]]和輸出:[[1,1],[1,1],[1, 1],[1,2],[1,2,3]]' –

+0

好挑戰!我喜歡! –

1

可能,這將有助於

def flat(array) 
    array.each do |item| 
    if item.is_a?(Array) && item.flatten.count != item.count 
     flat(item) 
    else 
     $arr << item 
    end 
    end 
end 

### 
$arr = [] 
collection = [[1, 1], [[1, 1], [1, 1], [[1, 2], [1, 2, 3]]]] 
flat(collection) 
puts $arr.inspect 

=> [[1, 1], [1, 1], [1, 1], [1, 2], [1, 2, 3]] 


$arr = [] 
collection = [[1,1],[[[1,1],[1,1]],[1,1]]] 
flat(collection) 
$arr 
=> [[1, 1], [1, 1], [1, 1], [1, 1]]