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 Scala

1 Answer

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

*/

 



answered 2 days ago by avibootz
...