Cartesian Product in Kotlin

The Cartesian product of two sets A and B, denoted by A x B, is the set of all ordered pairs (a, b) where a belongs to A and b belongs to B.

Formally, A x B = {(a, b) | a ∈ A, b ∈ B}

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

Kotlin
fun main() {
    val setA = setOf(1, 2, 3)
    val setB = setOf("A", "B", "C")
    val cartesianProduct = mutableSetOf<Pair<Int, String>>()
    for (a in setA) {
        for (b in setB) {
            cartesianProduct.add(Pair(a, b))
        }
    }
    println(cartesianProduct)
}

This code defines two sets, setA and setB, and then iterates through each element in setA and setB using nested loops. It adds each pair of elements to a mutable set called cartesianProduct. Finally, it prints the Cartesian product set to the console.

Output:

[(1, A), (1, C), (2, A), (2, C), (3, A), (3, C), (1, B), (2, B), (3, B)]

Leave a Comment