Ruby阵列平坦化
我有一个n深度数组,其中n是大于或等于2的变量:Ruby阵列平坦化,ruby,Ruby,我有一个n深度数组,其中n是大于或等于2的变量: [[1,1],[[1,1],[1,1]]] 我想将此阵列展平,使其正好有2个深度,如下所示: [[1,1],[1,1],[1,1]] 有人能想出一个好办法来实现这一点吗?这应该可以 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]]]
我想将此阵列展平,使其正好有2个深度,如下所示:
[[1,1],[1,1],[1,1]]
有人能想出一个好办法来实现这一点吗?这应该可以
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]]
试试这个:
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]]
def depth\u first\u展平阵列
结果=[]
数组。每个do |元素|
如果element.first.is_a?排列
结果+=深度(元素)
其他的
结果可能有帮助
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]]
def平面(阵列)
数组。每个do |项|
如果item.is_是?(数组)和&item.flatte.count!=项目.计数
单位(项目)
其他的
$arr[[1,1]、[1,1]、[1,1]、[1,2]、[1,2,3]]
$arr=[]
集合=[[1,1],[[1,1],[1,1],[1,1]]
公寓(收藏)
$arr
=> [[1, 1], [1, 1], [1, 1], [1, 1]]
不清楚您想要如何输出;e、 为什么[[1,1],[1,1]]
变成了[1,1],[1,1]
而不是[1,1,1]
?可能需要更多的案例才能得到有用的东西。但首先,你试过什么?也许有一个级别参数?有什么吗?我还测试了:array=[[1,2],[3,4],[5,6]],[7,8],[9,10][/code>,输出[[1,2],[3,4],[5,6],[7,8],[9,10]
测试了array=[1,1],[1,1],[1,1],[1,2],[1,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]!我喜欢!是的,这部作品在标题中写了“深度优先”这句话,让所有人都很反感。他在问题中给出的例子不是深度优先展平的结果。但看起来你的答案是他想要的。