How to group adjacent numbers that are the same

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

This is my input:

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

And the expected result:

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

So far I have 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 is equal, try a counter, perhaps, but it does not work.

+4
source share
3 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"
+6
source

chunk , , slice (slice_when Ruby 2.2):

[2, 2, 2, 3, 4, 3, 3, 2, 4, 4, 5].slice_when { |a, b| a != b }.map do |ints|
  if ints.size == 1
    ints[0]
  else
    "#{ints[0]}:#{ints.size}"
  end
end.join(',')
# "2:3,3,4,3:2,2,4:2,5"

, , select reject.

+2
arr = [2, 2, 2, 3, 4, 3, 3, 2, 4, 4, 5]

arr.drop(1).each_with_object([[arr.first, 1]]) do |e,a|
  a.last.first == e ? a[-1][-1] += 1 : a << [e, 1]
end.map { |a| a.join(':') }.join(',')
  #=> "2:3,3:1,4:1,3:2,2:1,4:2,5:1"
0
source

Source: https://habr.com/ru/post/1675513/


All Articles