user7055375
user7055375

Reputation:

How do I find the size of the longest subarray?

I'm using Ruby 2.4. I have an array of arrays

arr = [[1, 8, 9, 10], [2, 3, 7], [0, 2, 15, 4, 27, 3], [2]]

How do I find the maximum number of elements for all of the child arrays? For example, in the above, the answer would be 6 since the third array has 6 elements, more than the number of elements for the other arrays.

Upvotes: 1

Views: 511

Answers (5)

Sagar Pandya
Sagar Pandya

Reputation: 9508

max_by is the way to go here but you can use max too:

arr.max { |a, b| a.size <=> b.size }.size
#=> 6

Benchmarks

require 'fruity'
arr = Array.new(10000) { |arr| Array.new(rand 10) }

compare do
  maxby_size  { arr.max_by(&:size).size }
  maxby_count { arr.max_by(&:count).count }
  map_max     { arr.map(&:size).max }
  max         { arr.max { |a,b| a.size <=> b.size }.size }
  reduce      { arr.reduce(0) { |memo, a| memo > a.length ? memo : a.length } }
end

#Running each test 2 times. Test will take about 1 second.
#map_max is faster than max by 2x ± 0.1
#max is similar to reduce
#reduce is similar to maxby_size
#maxby_size is similar to maxby_count

Upvotes: 1

Ursus
Ursus

Reputation: 30071

It's so simple

arr.max_by(&:size).size
=> 6

Upvotes: 7

Eric Duminil
Eric Duminil

Reputation: 54293

It's really straightforward, even if you don't know max_by:

arr.map(&:size).max
#=> 6

Upvotes: 4

dawg
dawg

Reputation: 104082

Given:

> arr=[[1, 8, 9, 10], [2, 3, 7], [0, 2, 15, 4, 27, 3], [2]]

Use max_by:

> arr.max_by {|l| l.length}
=> [0, 2, 15, 4, 27, 3]

Or, the shortcut form:

> arr.max_by(&:length)
=> [0, 2, 15, 4, 27, 3]

And if you want 6 vs the actual array:

> arr.max_by {|l| l.length}.length
=> 6

Upvotes: 1

31piy
31piy

Reputation: 23869

You can use max_by on the array:

array.max_by { |i| i.length }.length

Upvotes: 1

Related Questions