Andres

Andres

Given a non-empty list of integers, every element appears twice except for one. Find that single one

Hello.

Trying to find the only element that does not appear twice I wrote the following algorithm:

list = [1, 2, 3, 1, 3, 10, 200, 10, 200] # Expected result => 2

def single_one(list) do
    list
    |> Enum.reduce(%MapSet{}, fn x, acc ->
      if MapSet.member?(acc, x) do
        MapSet.delete(acc, x)
      else
        MapSet.put(acc, x)
      end
    end)
    |> MapSet.to_list()
    |> hd()
end

I have the following questions:

  1. I would like to know if in Elixir it is good practice to use if else as I did in the previous algorithm.
    I could not find a way to access the first and only element of the MapSet.
    I proceeded to convert the MapSet into a list and then its head.
  2. Is there a better way to get the first element of a MapSet?

Any suggestions to improve the algorithm is welcome.

Thanks.

Marked As Solved

mudasobwa

mudasobwa

Creator of Cure

FWIW, I’d provide a bare implementation that is similar to MapSet (actually it replicates MapSet implementation, which is a bare map underneath):

[1, 2, 3, 1, 3, 10, 200, 10, 200] |> Enum.reduce(%{}, fn e, acc ->
  if is_nil(Map.get(acc, e)), do: Map.put(acc, e, e), else: Map.delete(acc, e)
end) |> Map.keys() |> hd()
#⇒ 2

Also Liked

mudasobwa

mudasobwa

Creator of Cure
use Bitwise
[1, 2, 3, 1, 3, 10, 200, 10, 200] |> Enum.reduce(0, &Bitwise.bxor/2)
#⇒ 2

:man_shrugging:

Qqwy

Qqwy

TypeCheck Core Team

You could also create a histogram (which takes O(n) time), and then drop all elements from it that have a count of ‘2’. You then end up with:

  1. either exactly one element, and you can output it
  2. Something that does not match the input you expect, and you’re now able to return or raise a proper error.

I think that might be a more robust solution, if you cannot be entirely sure that the input precondition is met by the user at all times. It will also work for non-integers. (Although the binary XNOR is a marvellous idea :heart_eyes:)

hauleth

hauleth

Classic methods are always the best one.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement