簡體   English   中英

Ruby在一個函數中從新創建的數組中獲取最大值

[英]Ruby Getting a max value out of a newly created array in one function

我希望我的函數返回嵌套數組(包括數組本身)內最長的數組,因此

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]

我創建了一個函數來收集所有數組。 我必須在另一個函數中獲取最大值。

我的代碼:

def deep_max(ary)
  ary.inject([ary]) { |memo, elem|
  if elem.is_a?(Array)
    memo.concat(deep_max(elem))
  else
    memo
  end }
end

這給了我我想要的東西:

deep_max(nested_ary).max_by{ |elem| elem.size }

有沒有辦法在函數內部獲得這個最大值?

您可以展開它:

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

或者,您可以通過引入一個可選參數來作弊,該參數可以更改遞歸在頂層的工作方式以及在兔子洞中的行為方式。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM