How do I make a combination of values ​​in a string using scala?

I want to concatenate values ​​in a string. eg,

Let A = a,b,c,d

      

I need a combination like

AComb = a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,bcd,acd

      

+3


source to share


1 answer


Suppose A

isSet

scala> val A =Set("a","b","c","d")
A: scala.collection.immutable.Set[String] = Set(a, b, c, d)


scala> val AComb=A.toSet[String].subsets.map(_.mkString).toVector
AComb: Vector[String] = Vector("", a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd)

      

I think you don't need this first element so you can try

scala> val AComb=A.toSet[String].subsets.map(_.mkString).toVector.tail
AComb: scala.collection.immutable.Vector[String] = Vector(a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd)

      



removing the first and last elements

scala> val AComb=A.toSet[String].subsets.map(_.mkString).toVector.init.tail
AComb: scala.collection.immutable.Vector[String] = Vector(a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd)

      

updated as per comment

scala> val xc1=Set("sunny","hot","high","FALSE","no")
xc1: scala.collection.immutable.Set[String] = Set(sunny, FALSE, hot, no, high)

scala> val AComb=xc1.toSet[String].subsets.map(_.mkString(" ")).toVector.tail;
AComb: scala.collection.immutable.Vector[String] = Vector(sunny, FALSE, hot, no, high, sunny FALSE, sunny hot, sunny no, sunny high, FALSE hot, FALSE no, FALSE high, hot no, hot high, no high, sunny FALSE hot, sunny FALSE no, sunny FALSE high, sunny hot no, sunny hot high, sunny no high, FALSE hot no, FALSE hot high, FALSE no high, hot no high, sunny FALSE hot no, sunny FALSE hot high, sunny FALSE no high, sunny hot no high, FALSE hot no high)

      

+5


source







All Articles