How to invert a map?

Viewed 1140

What I have:

%{1 => #MapSet<[123, 234, 345, 456, 567]>,
  2 => #MapSet<[345, 456, 567, 678, 789]>}

What I need:

%{123 => #MapSet<[1],
  234 => #MapSet<[1],
  345 => #MapSet<[1,2],
  456 => #MapSet<[1,2],
  567 => #MapSet<[1,2],
  678 => #MapSet<[2],
  789 => #MapSet<[2]}

I cannot seem to find such a function in elixir, and my attempts to write my own aren't going so well.

Edit:

I ended up with this as my final solution:

Enum.reduce(x, %{}, fn {k, vs}, acc ->
   Enum.reduce(vs, acc, fn v, acc ->
     update_in(acc[v], fn
       nil -> MapSet.new([k])
       set -> set |> MapSet.put(k)
     end)
   end)
 end)
2 Answers
Related