rosy
rosy

Reputation: 146

How to combine two tuples in scala?

I want to combine two tuples, for example

My Tuples are:

(a,b)
(a,c)
(d,a)
(d,c)

I want the combination as,

(a,b,c)                // Ist & IInd tuple
(a,b,d)                // Ist & IIIrd tuple
(a,b,d,c)              // Ist & IVth tuple
(a,c,d)                // IInd & IIIrd tuple  ( IInd & IVth is also same)

Here I initially combine the first tuple with second tuple, third tuple and finally last tuple. Then I take the second tuple and combine it with third tuple and fourth tuple. Finally I take third tuple and combine it with the remaining last tuple. Remember If we combine two tuples, if the same combination values are occur, remove the duplicate tuples

Upvotes: 2

Views: 5011

Answers (2)

Jatin
Jatin

Reputation: 31724

Well it is quite difficult with tuples if you want them as output. If a set will do then:

scala> List(('a,'b), ('a,'c), ('d,'a), ('d,'c)).combinations(2).map(
                                y => y.flatten(_.productIterator).toSet).toSet

res42: scala.collection.immutable.Set[scala.collection.immutable.Set[Any]] = 
 Set(Set('a, 'b, 'c), Set('a, 'b, 'd), Set('a, 'b, 'd, 'c), Set('a, 'c, 'd))

Upvotes: 4

Ashalynd
Ashalynd

Reputation: 12563

Something like that might work

val tuples = List(('a','b'),('a','c'),('d','a'),('d','c'))

def combine (tuples: List[(Char,Char)]) = {
val combinations = for {
    t1<- tuples
    t2<- tuples
    if (t1!=t2)
} yield {
    Set(t1._1,t1._2,t2._1,t2._2).toList.sorted
combinations.toSet }

Upvotes: 1

Related Questions