scala - How to compute inverse of a multi-map -



scala - How to compute inverse of a multi-map -

i have scala map: x: [b,c] y: [b,d,e] z: [d,f,g,h]

i want inverse of map look-up. b: [x,y] c: [x] d: [x,z] , on.

is there way without using in-between mutable maps

if not multi-map - next works:

typemap.flatmap { case (k, v) => v.map(vv => (vv, k))}

edit: fixed reply include marth rightfully pointed out. reply bit more lenghty seek go through each step , not utilize magic provided flatmaps educational purposes, more straightforward :)

i'm unsure notation. assume have like:

val mymap = map[t, set[t]] ( x -> set(b, c), y -> set(b, d, e), z -> set(d, f, g, h) )

you can accomplish reverse lookup follows:

val instances = { keyvalue <- mymap.tolist value <- keyvalue._2 } yield (value, keyvalue._1)

at point, instances variable list of type:

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

if do:

val groupedlookups = instances.groupby(_._1)

you get:

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

now want cut down values contain sec part of each pair. hence do:

val reverselookup = groupedlookup.map(_._1 -> _._2.map(_._2))

which means every pair maintain original key, map list of arguments has sec value of pair.

and there have result.

(you can avoid assigning intermediate result, thought clearer this)

scala map

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Php operator `break` doesn't stop while -