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:
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.
Is there a better way to get the first element of a MapSet?
Any suggestions to improve the algorithm is welcome.
In cases like this, where you check for a boolean result, if/else is usually used instead of case, so itās good as is .
I donāt think there is, because there is no āfirstā element in a MapSet. In this case, you know that there is only a single one, but in the more general case, elements inside a MapSet are not ordered. So if you have more than a single element in a set, there is no idea which element youād obtain when extracting a single one from it.
I donāt think there is, because there is no āfirstā element in a MapSet.
Could you be so kind to explain me how I can refer to the first element of a MapSet? Or what do you mean there is not a first element in a MapSet?
The official definition of MapSet says the following:
A set can contain any kind of elements, and elements in a set donāt have to be of the same type.
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:
either exactly one element, and you can output it
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 )