0

I have a constantly-updating mutable.HashMap[String, String] with a record of current user locations:

{user1 -> location1,
 user2 -> location4,
 user3 -> location4}

I want to keep track of the location co-occurences between users - that is, how many times each pair of users has been in the same location. The format I have in mind is a mutable.HashMap[(String, String), Int]:

{(user1, user2) -> 0,
 (user1, user3) -> 0,
 (user2, user3) -> 1}

Each time the user location map updates, I want to re-examine which users are together and add 1 to their running count of co-occurences.

The code below returns a map of {location -> Array(users)}, which feels like a good first step.

var users_by_location = user_locations.groupBy(_._2).mapValues{s => s.map{ case(user, location) => user}}

> {location1 -> Array(user1), location4 -> Array(user2, user3)}

I'm using scala 2.11.8.

p3zo
  • 61
  • 1
  • 8

1 Answers1

3

Use the subsets(2) to get all combinations of keys and compare whether equal to generate a new map, like:

val m = Map("user1" -> "location1", "user2" -> "location2", "user3" -> "location2")
val result = m.keySet.subsets(2).map(_.toList).map(i => (i.head, i(1))).map(i => if (m.get(i._1) == m.get(i._2)) (i, 1) else (i, 0)).toMap
println(result)
> Map((user1,user2) -> 0, (user1,user3) -> 0, (user2,user3) -> 1)
chengpohi
  • 14,064
  • 1
  • 24
  • 42