gpt4 book ai didi

scala - 如何使用 Scala 组合字符串中的值?

转载 作者:行者123 更新时间:2023-12-01 11:36:44 25 4
gpt4 key购买 nike

我想将值组合成一个字符串。例如,

Let A = a,b,c,d

我想要这样的组合,

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

最佳答案

我假设 A 是一个 Set

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)

关于scala - 如何使用 Scala 组合字符串中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com