Reputation: 1851
I have a list of tuples, where each tuple is of type (String, String)
.
A sample list can be: List((A,B), (A,C), (A,D), (A,E), (B,C), (B,A), (B,D), (B,E), (C,A), (C,B), (C,D), (C,E),...)
.
I want to do two things on this list:
A
should be shuffled in a random order, but should stay together. For Example, it may then look like: (A,E),(A,D),(A,B),(A,C),(B,A),(B,E),(B,C),(B,D)...
etc.I'm not able to figure out the logic for both of them combined, because if we do Random.shuffle()
and then a .take()
, it might take
in any given order, not necessarily 3 for each of the first element.
Upvotes: 1
Views: 200
Reputation: 22850
If I understand you correctly, you want something like this:
def pickNRandomByKey[K : Ordering, V](n: Int)(data: List[(K, V)]): List[(K, List[V])] =
data
.groupMap(_._1)(_._2)
.view
.mapValues(group => Random.shuffle(group).take(n))
.toList
.sortBy(_._1)
Upvotes: 3
Reputation: 7604
You can first group by the first element, shuffle the inner lists, and then extract 3 tuples from those lists and flatten at the end
list.groupBy(_._1).map { case (k, v) => Random.shuffle(v).take(3) }.flatten
Output will look something like:
List((A,C), (A,B), (A,E), (B,A), (B,C), (B,E), (C,E), (C,D), (C,A), (D,C), (D,A), (D,B) ...)
Upvotes: 3