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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

How to find the N smallest values in a 2D array in Kotlin

1 Answer

0 votes
/*
    Find the N smallest values in a 2D array.

    Approach:
    1. Flatten the 2D array into a single list.
    2. Sort the list.
    3. Take the first N values.

    Kotlin's standard library provides expressive and efficient
    operations for transforming and selecting data.
*/

// Flatten a 2D array into a 1D list
fun flatten(matrix: Array<IntArray>): List<Int> {
    // matrix.flatMap works because the array is only 2 levels deep
    return matrix.flatMap { row -> row.toList() }
}

// Extract the N smallest values
fun smallestN(matrix: Array<IntArray>, n: Int): List<Int> {
    val flat: List<Int> = flatten(matrix)

    // Sort ascending
    val sorted: List<Int> = flat.sorted()

    // Return the first N values
    return sorted.take(n)
}

fun main() {
    val matrix: Array<IntArray> = arrayOf(
        intArrayOf(42, 12, 85, 3),
        intArrayOf(7, 99, 15, 23),
        intArrayOf(64, 1, 18, 30),
        intArrayOf(3, 55, 11, 90)
    )

    val n: Int = 5

    val values: List<Int> = smallestN(matrix, n)

    println("The $n smallest values:")
    println(values.joinToString(" "))
}


/*
run:

The 5 smallest values:
1 3 3 7 11

*/

 



answered 2 days ago by avibootz
...