Remove adjacent identical elements in a Ruby Array?

前端 未结 6 1693
醉酒成梦
醉酒成梦 2021-02-14 12:55

Ruby 1.8.6

I have an array containing numerical values. I want to reduce it such that sequences of the same value are reduced to a single instance of that value.

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 13:30

    Unless you are very concerned with the speed that block will calculate at, I would suggest you simply add this line to the end of your block to get the desired output:

    a.compact!
    

    That will just remove all the nil elements you introduced to the array earlier (the would-be duplicates), forming your desired output: [1, 2, 3, 2, 3]

    If you want another algorithm, here is something far uglier than yours. :-)

    require "pp"
    
    a = [1, 1, 1, 2, 2, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3]
    
    i = 0
    
    while i < a.size do
      e = a[i]
      j = i
    
      begin
        j += 1
      end while e == a[j]
    
      for k in i+1..j-1 do
        a[k] = nil
      end
    
      i = j
    end
    
    pp a
    a.compact!
    pp a
    

    Gives you the output:

    [1, nil, nil, 2, nil, 3, nil, nil, nil, 2, nil, nil, 3, nil, nil]
    [1, 2, 3, 2, 3]
    

    In my opinion, your code is fine. Just add the a.compact! call and you are sorted.

提交回复
热议问题