[英]Ruby Getting a max value out of a newly created array in one function
I want my function to return the longest Array within a nested array (including the array itself) so 我希望我的函数返回嵌套数组(包括数组本身)内最长的数组,因此
nested_ary = [[1,2],[[1,2,[[1,2,3,4,[5],6,7,11]]]],[1,[2]]
deep_max(nested_ary)
=> [1,2,3,4,[5],6,7,11]
simple_ary = [1,2,3,4,5]
deep_max(simple_ary)
=> returns: [1,2,3,4,5]
I created a function to collect all arrays. 我创建了一个函数来收集所有数组。 I have to get the max value in another function.
我必须在另一个函数中获取最大值。
my code: 我的代码:
def deep_max(ary)
ary.inject([ary]) { |memo, elem|
if elem.is_a?(Array)
memo.concat(deep_max(elem))
else
memo
end }
end
This gives me what I want: 这给了我我想要的东西:
deep_max(nested_ary).max_by{ |elem| elem.size }
Is there a way to get this max inside of the function? 有没有办法在函数内部获得这个最大值?
You can unroll it: 您可以展开它:
def deep_max(ary)
arys = []
ary = [ary]
until ary.empty?
elem = ary.pop
if elem.is_a?(Array)
ary.push(*elem)
arys.push(elem)
end
end
arys.max_by(&:size)
end
Or you can cheat, by introducing an optional parameter that changes how your recursion works on top level vs how it behaves down the rabbit hole. 或者,您可以通过引入一个可选参数来作弊,该参数可以更改递归在顶层的工作方式以及在兔子洞中的行为方式。
def deep_max(arr)
biggest_so_far = arr
arr.each do |e|
if e.is_a?(Array)
candidate = deep_max(e)
biggest_so_far = candidate if candidate.size > biggest_so_far.size
end
end
biggest_so_far
end
deep_max [[1, 2], [[1, 2, [[1, 2, 3, 4, [5], 6, 7, 11]]]], [1, [2]]]
#=> [1, 2, 3, 4, [5], 6, 7, 11]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.