Get maximum consecutive value values ​​in an array

Is there a more elegant way to achieve this below:

Input:

array = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0] 

Conclusion:

 4 

My algorithm:

 streak = 0 max_streak = 0 arr.each do |n| if n == 1 streak += 1 else max_streak = streak if streak > max_streak streak = 0 end end puts max_streak 
+5
source share
4 answers

Like w0lf answer , but skipping elements, returning nil from chunk :

 array.chunk { |x| x == 1 || nil }.map { |_, x| x.size }.max 
+6
source

Edit : Another way to do this (this is less general than Stefan's answer, as you will have to smooth and split again if there was a different number other than 0 and 1, but use in this case):

 array.split(0).max.count 

You can use:

 array.chunk { |n| n }.select { |a| a.include?(1) }.map { |y, ys| ys.count}.max 

ref: Read successive occurrences of an element in a ruby ​​array

+6
source

You can use Enumerable#chunk :

 p array.chunk{|x| x}.select{|x, xs| x == 1}.map{|x, xs| xs.size }.max 

This is more eloquent, but if performance is important, I would use your approach.


Edit: if you are in Ruby 2.2.2, you can also use the new Enumerable#slice_when (if your input array consists of only 0 and 1 s):

 array.slice_when{|x,y| x < y }.map{|slice| slice.count 1 }.max 
+5
source

What about

 array = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0] 

array.split(0).group_by(&:size).max.first #=> 4

The only bad thing is split(0)

Note. This only works with ActiveSupport rails (extends C # split array)

Only for implementation with ruby ​​only

 array.join.split("0").group_by(&:size).max.first #=> 4 
0
source

All Articles