Elixir-lang Search for non-duplicate items in a list

I am trying to find non-duplicate values ​​from a list, for example.

source list:

iex> list = [2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 10] [2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 10] iex> unique = Enum.uniq(list) [2, 3, 4, 5, 6, 7, 8, 9, 10] iex> nondupes = unique -- Enum.uniq(list -- unique) [2, 3, 5, 7] 

result: [2, 3, 5, 7]

I was wondering if there is a better way to achieve this in elixir / erlang

+7
elixir
source share
2 answers

Another method (not necessarily the best), which may be faster for big data, is to build a map from the elements in their calculations and select those where count is 1:

 list |> Enum.reduce(%{}, fn (el, acc) -> Dict.put(acc, el, Dict.get(acc, el, 0) + 1) end) |> Enum.filter(fn {key, val} -> val == 1 end) |> Enum.map(fn {key, val} -> key end) 

It should be the runtime of O(n * log(n)) instead of O(n ^ 2) , which requires your solution (subtraction should be quadratic if the entire input is unique already).

+10
source share

REDO

(As Pavel noted, I did not answer the question, but only turned to the unifying bat. Therefore, I went overboard for fun below.)

Here is a purely recursive single-pass method for comparison only:

 -module(nondupes). -export([leave_uniques/1]). leave_uniques(L) -> lists:reverse(lu(lists:sort(L))). lu(L = [H,H|_]) -> lu(L, [], dupe); lu([H|T]) -> lu(T, [H], solo). lu([H,H], A, dupe) -> A; lu([_,H], A, dupe) -> [H|A]; lu([H,H], A, solo) -> A; lu([P,H], A, solo) -> [P,H|A]; lu([H | T = [H|_]], A, dupe) -> lu(T, A, dupe); lu([_ | T], A, dupe) -> lu(T, A, solo); lu([H | T = [H|_]], A, solo) -> lu(T, A, dupe); lu([P | T], A, solo) -> lu(T, [P|A], solo). 

If past experience is some kind of judge, it is probably more effective on large lists than a choice / set of subtractions - but past experience also tells me that most of the time is not really very important. In any case, it was something interesting.

Using:

 2> nondupes:leave_uniques([2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 10]). [2,3,5,7] 
0
source share

All Articles