Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove consecutive duplicates in Julia

I am quite new in Julia and I don't know how to remove consecutive duplicates in an array. For example if you take this array :

   `v=[8,8,8,9,5,5,8,8,1];`

I would like to obtain the vector v1 such that:

v1 = [8,9,5,8,1];

Could anyone help me? Many thanks.

like image 464
Samy Jelassi Avatar asked Apr 09 '16 13:04

Samy Jelassi


3 Answers

One method could be to define:

function fastuniq(v)
  v1 = Vector{eltype(v)}()
  if length(v)>0
    laste = v[1]
    push!(v1,laste)
    for e in v
      if e != laste
        laste = e
        push!(v1,laste)
      end
    end
  end
  return v1
end

And with this function, you have:

julia> println(fastuniq(v))
[8,9,5,8,1]

But, when dealing with arrays, one need to decide if elements are to be deep or shallow copied. In case of integers, it doesn't matter.

like image 198
Dan Getz Avatar answered Oct 07 '22 16:10

Dan Getz


In StatsBase.jl there is an rle function (Run-length encoding) that does exactly this.

like image 32
Neal Fultz Avatar answered Oct 07 '22 15:10

Neal Fultz


This is a lot slower than @DanGetz's function but here is a way to do it in one line:

function notsofastunique(v)
  return [v[1]; v[2:end][v[2:end] .!= v[1:end-1]]]
end


>println(notsofastunique(v))
[8,9,5,8,1]

Maybe it's useful for someone looking for a vecotrised solution.

like image 5
niczky12 Avatar answered Oct 07 '22 17:10

niczky12