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 Swift

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.

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

// Flatten a 2D array into a 1D array
func flatten(_ matrix: [[Int]]) -> [Int] {
    // flatMap converts each row into its elements and concatenates them
    matrix.flatMap { $0 }
}

// Extract the N smallest values
func smallestN(_ matrix: [[Int]], n: Int) -> [Int] {
    let flat: [Int] = flatten(matrix)

    // Sort ascending
    let sorted: [Int] = flat.sorted()

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

func main() {
    let matrix: [[Int]] = [
        [42, 12, 85,  3],
        [ 7, 99, 15, 23],
        [64,  1, 18, 30],
        [ 3, 55, 11, 90]
    ]

    let n: Int = 5

    let values: [Int] = smallestN(matrix, n: n)

    print("The \(n) smallest values:")
    print(values.map(String.init).joined(separator: " "))
}

main()


/*
run:

The 5 smallest values:
1 3 3 7 11

*/

 



answered 2 days ago by avibootz
...