Split into multiple Scala suites
I also have a Set[String]
number devider: Int
. I need to split the set randomly into chunks, each of which is sized devider
. Examples:
1.
Set: "a", "bc", "ds", "fee", "s"
devider: 2
result:
Set1: "a", "bc"
Set2: "ds", "fee"
Set3: "s"
2.
Set: "a", "bc", "ds", "fee", "s", "ff"
devider: 3
result:
Set1: "a", "bc", "ds"
Set2: "fee", "s", "ff"
3.
Set: "a", "bc", "ds"
devider: 4
result:
Set1: "a", "bc", "ds"
What's the idiomatic way to do this in Scala
?
source to share
You probably want something like:
Set("a", "bc", "ds", "fee", "s").grouped(2).toSet
The problem is that a is Set
by definition no order, so it doesn't tell you which elements will be grouped together.
Set( "a", "bc", "ds", "fee", "s").grouped(2).toSet
//res0: Set[Set[String]] = Set(Set(s, bc), Set(a, ds), Set(fee))
To group them in a specific way, you need to change Set
to one of the ordered collections, reorder the items as needed, group them and translate everything back to Set
s.
source to share