2014-10-04 48 views
3

我想結合字符串中的值。 例如,如何使用scala組合字符串中的值?

Let A = a,b,c,d 

我想要的組合,

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

更新'設A = A,B,C,D'?你的意思是'val A = Set(「a」,「b」,「c」,「d」)'? – 2014-10-04 05:12:25

回答

5

我假設ASet

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) 

我在想,你並不需要首先元素,所以你可以試試

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) 

除去第一和最後的元件

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) 

根據評

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) 
+0

如何刪除最後一個元素?我只需要n-1組合 – rosy 2014-10-04 05:31:49

+0

錯誤:(144,28)類型參數[字符串]不符合方法toSet的類型參數邊界[B>:Any] val AComb = xc1.toSet [String] .subsets.map( _.mkString).toVector.init.tail ^ – rosy 2014-10-04 05:45:01

+0

我聲明我的設置爲Set [Any],那就是問題所在。所以我把它改成Set [String]。它返回空值,即。 () – rosy 2014-10-04 05:52:30