/*
Find the N smallest values in a 2D array.
Approach:
1. Flatten the 2D array into a single sequence.
2. Sort the sequence.
3. Take the first N values.
Scala's collection library provides expressive and efficient
operations for transforming and selecting data.
*/
object SmallestNValues {
// Flatten a 2D array into a 1D list
def flatten(matrix: Array[Array[Int]]): List[Int] = {
// matrix.flatten works because the array is only 2 levels deep
matrix.flatten.toList
}
// Extract the N smallest values
def smallestN(matrix: Array[Array[Int]], n: Int): List[Int] = {
val flat: List[Int] = flatten(matrix)
// Sort ascending
val sorted: List[Int] = flat.sorted
// Return the first N values
sorted.take(n)
}
def main(args: Array[String]): Unit = {
val matrix: Array[Array[Int]] = Array(
Array(42, 12, 85, 3),
Array( 7, 99, 15, 23),
Array(64, 1, 18, 30),
Array( 3, 55, 11, 90)
)
val n: Int = 5
val values: List[Int] = smallestN(matrix, n)
println(s"The $n smallest values:")
println(values.mkString(" "))
}
}
/*
run:
The 5 smallest values:
1 3 3 7 11
*/