user8810618
user8810618

Reputation: 115

can not show result in scala using println

I am developing a scala script that gives all distinct combinations of elements of an array. For example, assume we have the Array(1,3,6,7). So, the needed results should be like : Array((1,3),(1,6),(1,7),(3,6),(3,7),(6,7))

 val test : Array[Int] = Array(1,3,6,7)
  val result = test.distinct.combinations(2).flatMap{ case Array(a,b) =>
    Array((a,b))
  }
  println(result)

But this code does not print the needed result.

EDIT

For added need, the initial table should have strings and not integers(this was just for operations tests). Asuume that I have the list val test = List("test", "tabdc", "efjh", "hlmn") And as proposed by @Luis Miguel Mejía Suárez, I generated all combinaisons

val result: List[(String, String)] = List((test,tabdc), (test,efjh), (test,hlmn), (tabdc,efjh), (tabdc,hlmn), (efjh,hlmn))

using

val result = test.distinct.combinations(2).collect {
  case a :: b :: Nil =>
    (a, b)}.toList

Now, I should compare each couple generated by these pieces of code to construct a string according to these rules :

In other words:

In this example: the final result should be testabdctestabdc (the concatenation between all joined parts) How can I do it, please?

Upvotes: 1

Views: 357

Answers (2)

Guru Stron
Guru Stron

Reputation: 141895

result is Iterator which is lazy, so one way to print is materialize it using toSeq for example:

println(result.toSeq) // prints List((1,3), (1,6), (1,7), (3,6), (3,7), (6,7))

Upvotes: 1

Okey, multiple things are happening in this snippet.

  1. combinations returns an Iterator which is lazy by nature, so that is why you don't see any output; because it hasn't computed anything at all.
    You may try to solve that by adding a toArray at the end, but that will give you a wrong output.

  2. Arrays should not be used, especially not while learning, they are useful for Java interop and performance tunning, but normal Scala code shouldn't wonder about those things.
    The list of reasons for not using Arrays include: they are mutable, they are invariant, they are not part of the collections hierarchy, their equals is by reference instead of by value, and their toString doesn't pretty print the contents of the Array; that is why adding a toArray at the end won't fix the problem. Thus, rather we should use List everywhere.

  3. No need for that flatMap a simple map would work. However, since combinations can't guarantee the type safety of its output, is better to use collect just to be safe.

Thus the final code would be:

val test = List(1, 3, 6, 7)
val result = test.distinct.combinations(2).collect {
  case a :: b :: Nil =>
    (a, b)
}.toList

You can see the code running here.

Upvotes: 3

Related Questions