Andres

Andres

Return true if a list has duplicates otherwise false

Hello.
I’m trying to check if a list has duplicates.
I didn’t have problems doing it with length and size:

def duplicate(list) do
    a = length(list)
    b = MapSet.size(MapSet.new(list))
    a !== b
end

I also did it with Enum and pattern matching but I’m pretty sure there is a better way:

defmodule Checker do
    def check(x) when is_boolean(x), do: x
    def check(x), do: false
end

def main(list) do
    list
    |> Enum.reduce_while(%MapSet{}, fn x, acc ->
      if x not in acc, do: {:cont, MapSet.put(acc, x)}, else: {:halt, true}
    end)
    |> Checker.check()
end

Could you help me to improve the last implementation in a more idiomatic way?

Thanks.

Marked As Solved

alexiss

alexiss

Agree, I miss it. The final proposal whould be:

def has_duplicates?(list) do
  list
  |> Enum.reduce_while(%MapSet{}, fn x, acc ->
    if MapSet.member?(acc, x), do: {:halt, false}, else: {:cont, MapSet.put(acc, x)}
  end)
  |> is_boolean()
end

Also Liked

peerreynders

peerreynders

Alternately shamelessly repurposing the implementation (uniq_list/3) of Enum.uniq/1:

defmodule Demo do
  def duplicates?(list),
    do: duplicates?(list, %{})

  defp duplicates?([], _) do
    false
  end

  defp duplicates?([head|tail], set) do
    case set do
      %{^head => true} ->
        true
      _ ->
        duplicates?(tail, Map.put(set, head, true))
    end
  end

  def run(list) do
    list
    |> duplicates?()
    |> inspect()
    |> IO.puts()
  end
end

list = [1, 2, 3, 3, 2, 1]
uniq_list = Enum.uniq(list)
Demo.run(list)      # true
Demo.run(uniq_list) # false

A lot can be learned by scouring through Elixir’s source code. The important thing is to understand how it works.

NobbZ

NobbZ

But reducing and finding the elements in a list again results in a runtime of O(n log n), using a MapSet is O(n).

l00ker

l00ker

Maybe something like this:

def has_duplicates?(list), do: Enum.uniq(list) != list

Last Post!

silverdr

silverdr

Alternatively (ab)using (instead of repurposing) the implementation of Enum.uniq/1

!Enum.empty?(list -- Enum.uniq(list))

?

Probably wouldn’t use it for huuge lists though :wink:

Where Next?

Popular in Questions Top

RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44139 214
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement