treeshateorcs
treeshateorcs

Reputation: 467

Ruby count adjacent duplicate elements in array

Given an array, say %w[ a b c a a b b c c c]. The method should return 3, as it is the maximum quantity of adjacent duplicates ( 3 'c' )

This is what I came up with so far:

def check_quantity_of_same_adjacent_elements(array)
  max = 0
  array.each_index do |i|
    max += 1 if array[i] == array[i+1]
  end
  max
end

but it obviously don't work as it returns the number of all duplicates

Upvotes: 0

Views: 632

Answers (1)

sawa
sawa

Reputation: 168101

%w[a b c a a b b c c c].chunk{|e| e}.map{|_, v| v.length}.max #=> 3

Upvotes: 2

Related Questions