2017-07-01 9 views
2

ネストされた配列をとり、最も長い配列のサイズを返したい関数を書いてみたいと思います。サイズがネストされた配列の中で最も長い配列を見つけて返す

max_with_size([])          # [0, []] 
max_with_size([2,3,4])         # [3, [2, 3, 4]] 
max_with_size([1,[2,3,4]])        # [3, [2, 3, 4]] 
max_with_size([[5,[6],[7,8,9],10,11]])     # [5, [5, [6], [7, 8, 9], 10, 11]] 
max_with_size([[1,[2,3,4]],[[[5,[6],[7,8,9],10,11]]]]) # [5, [5, [6], [7, 8, 9], 10, 11]] 

これまでのところ私が持っているこの

def max_with_size (ary) 
    max_size = ary.size 
    max_ary = ary 
    ary.each { |elem| 
    if elem.is_a? Array 
     if elem.size > max_size 
     max_size = max_with_size(elem)[0] 
     max_ary = max_with_size(elem)[1] 
     end 
    end 
    } 
    [max_size, max_ary] 
end 

それは最初の4例のために正常に動作しますが、第5回は失敗し、これだけ

max_with_size([[1,[2,3,4]],[[[5,[6],[7,8,9],10,11]]]]) # [2, [[1, [2, 3, 4]], [[[5, [6], [7, 8, 9], 10, 11]]]]] 

は、私がどのように達成することができます提供します欲しい結果は?

答えて

3

次のコードは、目的の結果を出力します。私はインラインコメントでコードを説明しました。

#Initialize @max to empty array, @max is an array with two elements, like this: [max_array_size, max_array] 
@max = [] 

def max_with_size(array) 
    # when @max is empty or when array size is greater than what is store in @max, store array size and array contents in @max 
    (@max = [array.size, array]) if @max.empty? || (@max[0] < array.size) 

    #Iterate through each element in array 
    array.each do |x| 

    #Skip to next element if x is not an array 
    next unless x.is_a? Array 
    #Recursively find max of array x 
    max_with_size(x) 
    end 
    @max 
end 
2

コード

def max_arr(arr) 
    [arr, *arr.each_with_object([]) {|e,a| a << max_arr(e) if e.is_a?(Array) && e.any?}]. 
    max_by(&:size) 
end 

examples = [[], 
      [2,3,4], 
      [1,[2,3,4]], 
      [[5,[6],[7,8,9],10,11]], 
      [[1,[2,3,4]],[[[5,[6],[7,8,9],10,11]]]], 
      [1, [2, [3, 4, [6, 7, 8, 9, 10], [11, 12]], 13]]] 

examples.each do |arr| 
    a = max_arr(arr) 
    puts "\n#{arr}\n \#=> #{a.size}, #{a}" 
end· 

[] 
    #=> 0, [] 

[2, 3, 4] 
    #=> 3, [2, 3, 4] 

[1, [2, 3, 4]] 
    #=> 3, [2, 3, 4] 

[[5, [6], [7, 8, 9], 10, 11]] 
    #=> 5, [5, [6], [7, 8, 9], 10, 11] 

[[1, [2, 3, 4]], [[[5, [6], [7, 8, 9], 10, 11]]]] 
    #=> 5, [5, [6], [7, 8, 9], 10, 11] 

[1, [2, [3, 4, [6, 7, 8, 9, 10], [11, 12]], 13]] 
    #=> 5, [6, 7, 8, 9, 10] 
関連する問題