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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With