'How to generate every combination of a Map in Scala
val monies: Map[String, Double] = Map(
"USD-EUR" -> 0.7473154,
"EUR-GBP" -> 0.0097373,
"GBP-USD" -> 136.6080875,
"COL-USD" -> 1.0000000,
"ABC-XYZ" -> 1.00034500,
"XYZ-ABC" -> 1.000345000
)
I want to create a List[Map[String, Double]] which has every possible combination of the Map above.
In the final List of Maps, each Map must have a minimum of three currencies (i.e. any Maps with less than 3 entries must be excluded).
The Map provided may have 3 currencies or may have 50. Meaning the solution must be scalable for example if any new country was established along with a new currency.
List(
Map(
"USD-EUR" -> 0.7473154,
"EUR-GBP" -> 0.0097373,
"GBP-USD" -> 136.6080875
),
Map(
"EUR-GBP" -> 0.0097373,
"USD-EUR" -> 0.7473154,
"GBP-USD" -> 136.6080875
),
Map(
"EUR-GBP" -> 0.0097373,
"GBP-USD" -> 136.6080875,
"USD-EUR" -> 0.7473154
),
Map(
"USD-EUR" -> 0.7473154,
"EUR-GBP" -> 0.0097373,
"GBP-USD" -> 136.6080875,
"COL-USD" -> 1.0000000,
),
Map(
"EUR-GBP" -> 0.0097373,
"USD-EUR" -> 0.7473154,
"GBP-USD" -> 136.6080875,
"COL-USD" -> 1.0000000,
),
.... etc etc
)
Please note unique can mean a different a different order of the entries. Also different length of Map size. Key must point to original values.
Solution 1:[1]
It seems all you need is this:
def getSubMaps[K, V](map: Map[K, V]): Iterator[Map[K, V]] =
map
.keySet
.subsets
.filter(keys => keys.sizeIs >= 3)
.map(keys => keys.map(key => key -> map(key)).toMap)
Since the result can be too big it is better to return an Iterator that will lazily produce the values required. You can always call toList at the end if you really need all of them in memory.
As I always say, the Scaladoc is your friend.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luis Miguel MejÃa Suárez |
