【问题标题】:Find and return the longest array in a nested array with its size查找并返回嵌套数组中最长的数组及其大小
【发布时间】:2017-12-05 13:54:13
【问题描述】:

我想编写一个函数,它接收一个嵌套数组并返回最长数组的大小及其本身。

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]]]]]

我怎样才能达到想要的结果?

【问题讨论】:

    标签: ruby algorithm recursion multidimensional-array


    【解决方案1】:

    以下代码应打印所需的结果。我用 Inline cmets 解释了代码。

    #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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-13
        • 1970-01-01
        • 2019-01-19
        • 2019-08-22
        • 1970-01-01
        • 2017-11-23
        • 2013-03-01
        相关资源
        最近更新 更多