To create a three-dimensional list in Kotlin, you can use nested lists where each inner list represents a 2D plane within the 3D space.
In this example,
fun main() {
val matrix3D = List(3) {
List(3) {
MutableList(3) { 0 }
}
}
for (i in matrix3D.indices) {
for (j in matrix3D[i].indices) {
for (k in matrix3D[i][j].indices) {
matrix3D[i][j][k] = i + j + k
}
}
}
println(matrix3D)
}
[[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[2, 3, 4], [3, 4, 5], [4, 5, 6]]]
In this example,
fun main() {
val matrix3D = List(2) {
List(2) {
MutableList(2) { "" }
}
}
for (i in matrix3D.indices) {
for (j in matrix3D[i].indices) {
for (k in matrix3D[i][j].indices) {
matrix3D[i][j][k] = "($i, $j, $k)"
}
}
}
println(matrix3D)
}
[[[(0, 0, 0), (0, 0, 1)], [(0, 1, 0), (0, 1, 1)]], [[(1, 0, 0), (1, 0, 1)], [(1, 1, 0), (1, 1, 1)]]]
In this tutorial, we learned How to create a Three Dimensional List in Kotlin language with well detailed examples.