Symmetric difference of two set in Kotlin

The symmetric difference of two sets A and B, denoted by A Δ B, is the set of all elements that are in A or B, but not in both.

Formally, A Δ B = {x | (x ∈ A and x ∉ B) or (x ∉ A and x ∈ B)}

In other words, the symmetric difference of two sets consists of all elements that are in one of the sets, but not in both.

For example, if A = {1, 2, 3} and B = {2, 3, 4}, then A Δ B = {1, 4}.

To compute the symmetric difference of two sets, you can use the following algorithm:

  1. Initialize an empty set C to represent the symmetric difference of A and B.
  2. For each element x in A, check if x is not in B. If x is not in B, add it to C.
  3. For each element y in B, check if y is not in A. If y is not in A, add it to C.
  4. The symmetric difference of A and B is now stored in C.
Kotlin
fun main() {
    val setA = setOf(1, 2, 3)
    val setB = setOf(2, 3, 4)
    val symmetricDifference = setA.symmetricDifference(setB)
    println(symmetricDifference)
}

This code defines two sets setA and setB and then calls the symmetricDifference function to find the symmetric difference of setA and setB. The symmetricDifference function returns a new set that contains all the elements in the first set or the second set, but not both.

Output:

[1, 4]

Leave a Comment