查找并返回嵌套数组中最长的数组及其大小

时间:2017-07-01 23:23:25

标签: ruby algorithm recursion multidimensional-array

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

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

我如何实现想要的结果?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

<强>代码

var myArray = { 
url: 'http://www.ozautoelectrics.com',
originalUrl: 'http://www.ozautoelectrics.com',
applications: [ { name: 'Font Awesome',
   confidence: '100',
   version: '',
   icon: 'Font Awesome.png',
   website: 'http://fontawesome.io',
   categories: [Object] },
 { name: 'Google Analytics',
   confidence: '100',
   version: '',
   icon: 'Google Analytics.svg',
   website: 'http://google.com/analytics',
   categories: [Object] },
 { name: 'jQuery',
   confidence: '100',
   version: '2.1.3',
   icon: 'jQuery.svg',
   website: 'http://jquery.com',
   categories: [Object] } 
   ]};
   
myArray.applications.forEach(function(value, index, array){
  console.log(value.categories); //Allow to access the array
  //console.log(value.categories[0]); //Allows the first element in the array
});


console.log('Arrow function Solution');
//solution with arrow function
myArray.applications.forEach((value, index, array) => {
  console.log(value.categories); //Allow to access the array
  //console.log(value.categories[0]); //Allows the first element in the array
});

<强>实施例

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