gosseti
gosseti

Reputation: 975

Compare two lists for similarity in Elixir

I have two lists of skills that I’d like to compare to provide a percentage score for how much of one list appears in the other:

user_skills = [
  %{name: "Elixir"}, 
  %{name: "Python"}
]

project_skills = [
  %{name: "Elixir"}, 
  %{name: "Erlang"}, 
  %{name: "Ruby"}
]

What percentage of user_skills appear in project_skills? What we’d want here is a result of 50%.

Upvotes: 3

Views: 1368

Answers (1)

Máté
Máté

Reputation: 2345

You can be very simple and use Kernel.--/2 to calculate the difference first:

iex(5)> user_skills -- project_skills
# [%{name: "Python"}]

You can then use the length of the original list user_skills and the length of the above operation to get a percentage like figure:

iex(6)> 1 - (length(user_skills -- project_skills) / length(user_skills))
0.5

If you'd like to do more sophisticated comparisons and diffs, take a look at the myers_difference as well.

Upvotes: 5

Related Questions