Get column values in a 2D matrix

Is there any library function to get column values in a 2D array that I can make use of instead of this ? Or is there any better way to extract this array ?

fun getColumn(matrix: Array<IntArray>, col: Int): IntArray {
    val nums = IntArray(matrix.size)

    for (i in nums.indices) {
        nums[i] = matrix[i][col]
    }

    return nums
}

You can shorten that a bit:
fun getColumn(matrix: Array<IntArray>, col: Int) = IntArray(matrix.size) { matrix[it][col] }

but I don’t think there’s much better in the standard lib.

1 Like

You should also understand that this is not really a 2D array. This is array of arrays. Java/Kotlin does not support multi-dimensional arrays and this is probably why there are no utils for them in stdlib. I believe there are 3rd party libs that add at least a partial support.

2 Likes