Cartesian product of two or more lists: Difference between revisions

Added Kotlin
(Added Kotlin)
Line 591:
 
[]</pre>
 
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
 
fun flattenList(nestList: List<Any>): List<Any> {
val flatList = mutableListOf<Any>()
 
fun flatten(list: List<Any>) {
for (e in list) {
if (e !is List<*>)
flatList.add(e)
else
@Suppress("UNCHECKED_CAST")
flatten(e as List<Any>)
}
}
 
flatten(nestList)
return flatList
}
 
operator fun List<Any>.times(other: List<Any>): List<List<Any>> {
val prod = mutableListOf<List<Any>>()
for (e in this) {
for (f in other) {
prod.add(listOf(e, f))
}
}
return prod
}
 
fun nAryCartesianProduct(lists: List<List<Any>>): List<List<Any>> {
require(lists.size >= 2)
return lists.drop(2).fold(lists[0] * lists[1]) { cp, ls -> cp * ls }.map { flattenList(it) }
}
 
fun printNAryProduct(lists: List<List<Any>>) {
println("${lists.joinToString(" x ")} = ")
println("[")
println("${nAryCartesianProduct(lists).joinToString("\n ", " ")}")
println("]\n")
}
 
fun main(args: Array<String>) {
println("[1, 2] x [3, 4] = ${listOf(1, 2) * listOf(3, 4)}")
println("[3, 4] x [1, 2] = ${listOf(3, 4) * listOf(1, 2)}")
println("[1, 2] x [] = ${listOf(1, 2) * listOf<Any>()}")
println("[] x [1, 2] = ${listOf<Any>() * listOf(1, 2)}")
println("[1, a] x [2, b] = ${listOf(1, 'a') * listOf(2, 'b')}")
println()
printNAryProduct(listOf(listOf(1776, 1789), listOf(7, 12), listOf(4, 14, 23), listOf(0, 1)))
printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf(500, 100)))
printNAryProduct(listOf(listOf(1, 2, 3), listOf<Int>(), listOf(500, 100)))
printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b')))
}</lang>
 
{{out}}
<pre>
[1, 2] x [3, 4] = [[1, 3], [1, 4], [2, 3], [2, 4]]
[3, 4] x [1, 2] = [[3, 1], [3, 2], [4, 1], [4, 2]]
[1, 2] x [] = []
[] x [1, 2] = []
[1, a] x [2, b] = [[1, 2], [1, b], [a, 2], [a, b]]
 
[1776, 1789] x [7, 12] x [4, 14, 23] x [0, 1] =
[
[1776, 7, 4, 0]
[1776, 7, 4, 1]
[1776, 7, 14, 0]
[1776, 7, 14, 1]
[1776, 7, 23, 0]
[1776, 7, 23, 1]
[1776, 12, 4, 0]
[1776, 12, 4, 1]
[1776, 12, 14, 0]
[1776, 12, 14, 1]
[1776, 12, 23, 0]
[1776, 12, 23, 1]
[1789, 7, 4, 0]
[1789, 7, 4, 1]
[1789, 7, 14, 0]
[1789, 7, 14, 1]
[1789, 7, 23, 0]
[1789, 7, 23, 1]
[1789, 12, 4, 0]
[1789, 12, 4, 1]
[1789, 12, 14, 0]
[1789, 12, 14, 1]
[1789, 12, 23, 0]
[1789, 12, 23, 1]
]
 
[1, 2, 3] x [30] x [500, 100] =
[
[1, 30, 500]
[1, 30, 100]
[2, 30, 500]
[2, 30, 100]
[3, 30, 500]
[3, 30, 100]
]
 
[1, 2, 3] x [] x [500, 100] =
[
]
 
[1, 2, 3] x [30] x [a, b] =
[
[1, 30, a]
[1, 30, b]
[2, 30, a]
[2, 30, b]
[3, 30, a]
[3, 30, b]
]
</pre>
 
=={{header|Perl 6}}==
9,485

edits