Identify runs on array with ruby

pattern-matching, ruby

Solution

try:

class Array
  def count_runs(element)
    chunk {|n| n}.count {|a,b| a == element && b.length > 1}
  end
end

a = [1, 1, 0, 0, 2, 3, 0, 0, 0, 3, 3, 3 ]
a.count_runs 0   #=> 2
a.count_runs 3   #=> 1
a.count_runs 1   #=> 1
a.count_runs 2   #=> 0

Problem

If we have an array ``` array = [1, 1, 0, 0, 2, 3, 0, 0, 0, 3, 3, 3 ] ``` How can we identify the run (amount of consecutive numbers with same value) of a given number? By example: ``` run_pattern_for(array, 0) -> 2 run_pattern_for(array, 3) -> 1 run_pattern_for(array, 1) -> 1 run_pattern_for(array, 2) -> 0 ``` There are no runs for 2 because there are no consecutive apparitions of two. There are one run for 3 because there are only one apparition with the tree as consecutive numbers.

Original source