2017-07-01 90 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]