ruby - Finding the length of repeating elements in an array -


i find length of streaks within following array:

states = [:read, :read, :read, :unread, :unread, :read, :read, :read, :read] 

the array has either :read or :unread, , want length of each streak of :read/:unread. states, become:

streak_lengths = [3, 3, 3, 2, 2, 4, 4, 4, 4] 

the array opens 3 :read elements, , label each of being part of 3 streak, has 2 :unread elements, they're each labelled 2 streak, , have streak of 4 read messages, they're each labelled 4.

what elegant, efficient , readable way solve above problem?

is recursion problem? while can solve problem, feel hints @ way of tackling i'm not familiar with. hints perhaps it's best solved recursion.

(for benefit of "possibly duplicate" flag applied this: both threads have different discussions. in addition search perspective, find other thread if search repeating characters, answer how detect repeating array elements. there load of excellent answers on here, removing question wouldn't make ecosystem richer, poorer)

chunk segments array consecutive elements have identical return value when block called on them. flat_map concats arrays returned block single one.

states.chunk(&:itself).flat_map{|_, a| array.new(a.length, a.length)} # => [3, 3, 3, 2, 2, 4, 4, 4, 4] 

perhaps can in recursive way if want, don't think lead elegant solution. experience, better avoid recursion whenever possible.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

json - Gson().fromJson(jsonResult, Myobject.class) return values in 0's -