Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Set into multiple Sets Scala

I have some Set[String] and a number devider: Int. I need to split the set arbitrary by pieces each of which has size 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 is the idiomatic way to do it in Scala?

like image 775
St.Antario Avatar asked Mar 22 '17 06:03

St.Antario


1 Answers

You probably want something like:

Set("a", "bc", "ds", "fee", "s").grouped(2).toSet

The problem is that a Set, by definition, has no order, so there's no telling 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 get them grouped in a particular fashion you'll need to change the Set to one of the ordered collections, order the elements as required, group them, and transition everything back to Sets.

like image 135
jwvh Avatar answered Oct 03 '22 07:10

jwvh