[英]How to count the number of arrays within an array in Ruby?
I can't seem to find an algorithm to compute the number of arrays within an array. 我似乎无法找到计算数组中数组数量的算法。 Example
例
Given 特定
[ [ "Array", "1" ], [ "Array", "2" ] ]
Output should be two 输出应该是两个
Given 特定
[
[
[ ["Array", "1"], ["Array", "2"] ],
[ ["Array", "3"], ["Array", "4"] ],
],
[
[ ["Array", "5"], ["Array", "6"] ],
[ ["Array", "7"], ["Array", "8"] ]
]
]`
Output should be 8 输出应为8
This recursive function will do the job for arrays of any nesting: 这个递归函数将完成任何嵌套数组的工作:
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
I suggest that you use a recursion function which would return 1 if the argument is a leaf array, for example: (if there are two children in each array as in the saas course exercise) 我建议你使用一个递归函数,如果参数是一个叶子数组,它将返回1,例如:(如果在saas课程练习中每个数组中有两个子节点)
def array?(entity)
entity[0].kind_of?(Array) ? array?(entity[0]) + array?(entity[1]) : 1
end
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
The result in this example is 14, not your requested 8. I count each array. 此示例中的结果是14,而不是您请求的8.我计算每个数组。
To get the 8 you must count only arrays without another array. 要获得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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.