4

is there a way in Scala to compare two sequences in a way that it returns true if it contains the same elements, regardless of order and repetitions?

Seq("1", "2") vs Seq("2", "1")           => true
Seq("3", "1", "2") vs Seq("2", "1", "3") => true
Seq("1", "1", "2") vs Seq("2", "1")      => true

Thanks

ps this is not a duplicated of this because it also asks to exclude duplicated from the check and it is using SEQ instead of LIST.

Community
  • 1
  • 1
ab_732
  • 3,639
  • 6
  • 45
  • 61
  • Possible duplicate of [Is there an API method that compares contents of a Seq irrespective of order?](http://stackoverflow.com/questions/3622895/is-there-an-api-method-that-compares-contents-of-a-seq-irrespective-of-order) – THIS USER NEEDS HELP Jan 03 '17 at 18:55

4 Answers4

13

Convert to sets and compare those

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
0
@ def sameElements[A](a: Seq[A], b: Seq[A]) = a.toSet == b.toSet
defined function sameElements
@ sameElements(Seq("1", "2"),Seq("2", "1"))
res2: Boolean = true
@ sameElements(Seq("3", "1", "2"),Seq("2", "1", "3"))
res3: Boolean = true
@ sameElements(Seq("1", "1", "2"),Seq("2", "1"))
res4: Boolean = true
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91
-1

Introduce an extension object with === operator. It will be used implicitly for the same typed Seqs

implicit class SeqOps[A](it:Seq[A]){
  def === (that:Seq[A]) = it.toSet == that.toSet
}

import Test.SeqOps

Seq("1", "2") === Seq("2", "1") shouldBe true
stanislav.chetvertkov
  • 1,620
  • 3
  • 13
  • 24
-3

You just need to turn the sequences to sets:

val n1: Seq[Int] = Seq(1, 3, 4)
    val n2: Seq[Int] = Seq(3, 4, 1)

    if(n1.toSet.equals(n2.toSet)){
      println("The sequences have the same elements.")
    }