All possible combinations of two lists

You could write these extension functions based on flatMap stdlib function:

// Extensions
fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> {
    return cartesianProduct(other, { first, second -> first to second })
}

fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> {
    return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } }
}

// Example
fun main(args: Array<String>) {
    val ints = listOf(0, 1, 2)
    val strings = listOf("a", "b", "c")

    // So you could use extension with creating custom transformer
    strings.cartesianProduct(ints) { string, int ->
        "$int $string"
    }.forEach(::println)

    // Or use more generic one
    strings.cartesianProduct(ints)
            .map { (string, int) ->
                "$int $string"
            }
            .forEach(::println)
}

A possible alternative:

fun <S, T> List<S>.cartesianProduct(other: List<T>) = this.flatMap {
    List(other.size){ i -> Pair(it, other[i]) } 
}

Edit - nicer, using zip syntax:

fun <S, T> List<S>.cartesianProduct(other : List<T>) : List<Pair<S, T>> =
    this.flatMap { s ->
        List(other.size) { s }.zip(other)
    }

Another (possibly more understandable) alternative to my previous answer. Both achieve the same result:

fun <S, T> List<S>.cartesianProduct(other: List<T>) = this.flatMap { thisIt ->
    other.map { otherIt ->
        thisIt to otherIt
    }
}

Tags:

Kotlin