Reputation: 115
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:
(test,tabdc)
: we have test
is ended by t
and
tabdc
begin with t
. So, they should be added as "testabdc
"((efjh,hlmn))
: we have efjh
is ended by h
and
hlmn
begin with h
. So, they should be added as : "efjhlmn
"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
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
Reputation: 22840
Okey, multiple things are happening in this snippet.
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.
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.
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