/*
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
*/