user4712458 user4712458 -4 years ago 108
Scala Question

Creating a string from the permutations of an ArrayBuffer[String] elements in Scala

I have

val a: String = "E"
val y: ArrayBuffer[String] = new ArrayBuffer("I", "G", "S")


I am trying to make a string, such that:

"(E <=> (I | G | S)) & (~I | ~G) & (~I | ~S) & (~G | ~S)"


Currently, for the first part of string (first clause)
(E <=> (I | G | S))
, I have this which is functional:

s"($a <=> (${y.mkString(" | ")}))" // & (~${y.mkString(" | ~")})"


For the second part, where are the permutations of elements in
y
, i.e., for
(~I | ~G) & (~I | ~S) & (~G | ~S)
, how I can improve (fix) the part within comments to create it?

I am trying to use the
y.permutations
, to create another string and then to concatenate with this one, but can it be "generated" here - within the same string in some way?

Thanks.

Answer Source

It seems from your example that what you need is combinations, not permutations.

So to have a term for every pair of elements from y you can find all combinations of length 2 using combinations method. Then you can wrap each pair in brackets in the necessary format, and finally build the whole second part with mkString:

y.combinations(2).map { case Seq(a, b) => s"(~$a | ~$b)" }.mkString(" & ")

You can integrate this expression into the string interpolation:

s"($a <=> (${y.mkString(" | ")})) & ${
  y.combinations(2).map { case Seq(a, b) => s"(~$a | ~$b)" }.mkString(" & ")}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download