我似乎无法找到计算数组中数组数量的算法。实施例
鉴于
[ [ "Array", "1" ], [ "Array", "2" ] ]
输出应该是两个
鉴于
[
[
[ ["Array", "1"], ["Array", "2"] ],
[ ["Array", "3"], ["Array", "4"] ],
],
[
[ ["Array", "5"], ["Array", "6"] ],
[ ["Array", "7"], ["Array", "8"] ]
]
]`
输出应为8
答案 0 :(得分:5)
这个递归函数将为任何嵌套的数组执行任务:
def count_subarrays array
return 0 unless array && array.is_a?(Array)
nested = array.select { |e| e.is_a?(Array) }
if nested.empty?
1 # this is a leaf
else
nested.inject(0) { |sum, ary| sum + count_subarrays(ary) }
end
end
答案 1 :(得分:0)
我建议你使用一个递归函数,如果参数是一个叶子数组,它将返回1,例如: (如果每个阵列中有两个孩子,如saas课程练习)
def array?(entity)
entity[0].kind_of?(Array) ? array?(entity[0]) + array?(entity[1]) : 1
end
答案 2 :(得分:0)
class Array
def deep_array_count()
count = 0
each{|el|
#I could check with is_a?(Array), but with respond_to? you could use your own classes.
if el.respond_to?(:deep_array_count)
count += 1 + el.deep_array_count
end
}
count
end
end
x = [
[
[
["Array", "1"], ["Array", "2"] ],
[ ["Array", "3"], ["Array", "4"] ],
],
[
[ ["Array", "5"], ["Array", "6"] ],
[ ["Array", "7"], ["Array", "8"] ]
]
]
p x.deep_array_count
此示例中的结果为14,而不是您请求的8。 我数每个数组。
要获得8,您必须只计算没有其他数组的数组。
class Array
def deep_array_count()
count = 0
each{|el|
#I could check with is_a?(Array), but with respond_to? you could use your own classes.
if el.respond_to?(:deep_array_count)
i = el.deep_array_count
count += i == 0 ? 1 : i #if no other array is inside, add 1
end
}
count
end
end
x = [
[
[
["Array", "1"], ["Array", "2"] ],
[ ["Array", "3"], ["Array", "4"] ],
],
[
[ ["Array", "5"], ["Array", "6"] ],
[ ["Array", "7"], ["Array", "8"] ]
]
]
p x.deep_array_count