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.

hauleth

hauleth

It can be pretty slow as you are iterating through all elements twice. Instead it is better to use:

inc = & &1 + 1
Enum.reduce(enumerable, %{}, &Map.update(&2, &1, 1, inc))

But in this case if this is homework and you know that the constraints will always hold then XOR solution by the @mudasobwa. If you do not know whether it will integer-only or you do not know if there will be only one value that occurs odd number of times, then second solution with map (however I would use Map.has_key?/2 or Map.fetch/2 instead of Map.get/2 as it is less quirky).

peerreynders

peerreynders

Elements in Maps and MapSets are not ordered. So whichever element appears “first” is “random”, i.e. is implementation dependent.

Where Next?

Popular in Questions Top

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
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 record...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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

Other popular topics Top

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
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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 record...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
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

We're in Beta

About us Mission Statement