Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group adjacent numbers that are the same

Tags:

ruby

I need to pack if there are at least two adjacent numbers which are same in the format <number : number_of_occurrences >.

This is my input:

[2,2,2,3,4,3,3,2,4,4,5]

And the expected output:

"2:3,3,4,3:2,2,4:2,5"

So far I tried:

a = [1, 1, 1, 2, 2, 3, 2, 3, 4, 4, 5]
a.each_cons(2).any? do |s , t|
  if s == t

If it's equal try a counter maybe, but thats not working.

like image 855
Sajeesh Krishnan Avatar asked Apr 24 '17 11:04

Sajeesh Krishnan


1 Answers

You can use Enumerable#chunk_while (if you're on Ruby >= 2.3):

a.chunk_while { |a, b| a == b }
 .flat_map { |chunk| chunk.one? ? chunk.first : "#{chunk.first}:#{chunk.size}" }
 .join(',')
#=> "2:3,3,4,3:2,2,4:2,5"

You can also use Enumerable#chunk (Ruby ~1.9.3, maybe earlier):

a.chunk(&:itself)
 .flat_map { |_, chunk| chunk.one? ? chunk.first : "#{chunk.first}:#{chunk.size}" }
 .join(',')
#=> "2:3,3,4,3:2,2,4:2,5"
like image 66
Andrey Deineko Avatar answered Oct 06 '22 19:10

Andrey Deineko