Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

How to calculate the median of a matrix in Kotlin

1 Answer

0 votes
fun findMedianUnsortedMatrix(matrix: Array<IntArray>): Double {
    val elements = mutableListOf<Int>()

    // Flatten the matrix
    for (row in matrix) {
        for (value in row) {
            elements.add(value)
        }
    }

    // Sort the elements
    elements.sort()

    // Calculate median
    val n = elements.size
    return if (n % 2 == 1) {
        // Odd number of elements: return middle element
        elements[n / 2].toDouble()
    } else {
        // Even number of elements: return average of two middle elements
        (elements[n / 2 - 1] + elements[n / 2]) / 2.0
    }
}

fun main() {
    val matrix = arrayOf(
        intArrayOf(5, 8, 9, 10),
        intArrayOf(1, 4, 6, 13),
        intArrayOf(7, 3, 0, 18),
        intArrayOf(6, 8, 9, 20)
    )

    val median = findMedianUnsortedMatrix(matrix)
    println("Median of the matrix is: %.1f".format(median))
}


/*
run:

Median of the matrix is: 7.5

*/

 



answered Oct 6, 2025 by avibootz
...