How to calculate multicard inversion

I have a Scala map: x: [b, c] y: [b, d, e] z: [d, f, g, h]

I want to get a backlink to this map for searching. b: [x, y] c: [x] d: [x, z] etc.

Is there a way to do this without using intermediate modified maps

If this is not a multi-card, then the following works:

typeMap.flatMap { case (k, v) => v.map(vv => (vv, k))}
+4
source share
2 answers

EDIT: A fixed answer to include what Mart rightly pointed out. My answer is a little longer than his, as I try to go through every step, and not use the magic provided by flatMaps for educational purposes, its more straightforward :)

I'm not sure about your notation. I assume you have something like:

val myMap = Map[T, Set[T]] (
  x -> Set(b, c),
  y -> Set(b, d, e),
  z -> Set(d, f, g, h)
)

:

val instances = for {
  keyValue <- myMap.toList
  value <- keyValue._2
}
yield (value, keyValue._1)

:

(b, x), (c, x), (b, y) ...

:

val groupedLookups = instances.groupBy(_._1)

:

b -> ((b, x), (b, y)),
c -> ((c, x)),
d -> ((d, y), (d, z)) ...

, . :

val reverseLookup = groupedLookup.map(_._1 -> _._2.map(_._2))

, , , .

.

( , , )

+5

:

def reverseMultimap[T1, T2](map: Map[T1, Seq[T2]]): Map[T2, Seq[T1]] =
  map.toSeq
    .flatMap { case (k, vs) => vs.map((_, k)) }
    .groupBy(_._1)
    .mapValues(_.map(_._2))

@Diego Martinoia , :

def reverseMultimap[T1, T2](myMap: Map[T1, Seq[T2]]): Map[T2, Seq[T1]] = {
  val instances = for {
    keyValue <- myMap.toList
    value <- keyValue._2
  } yield (value, keyValue._1)

  val groupedLookups = instances.groupBy(_._1)
  val reverseLookup = groupedLookups.map(kv => kv._1 -> kv._2.map(_._2))
  reverseLookup
}
0

All Articles