How to flatten a 2D array into a sorted one-dimensional array in Scala

1 Answer

0 votes
object Flatten2DArrayIntoSorted1DArray {

  // Function that flattens a 2D array and returns a sorted 1D array
  def flattenAndSort(array2d: Array[Array[Int]]): Array[Int] = {

    // 1. Flatten the 2D array into a single array
    //    flatten merges nested collections one level deep
    val flattened = array2d.flatten

    // 2. Sort the flattened array
    flattened.sorted
  }

  def main(args: Array[String]): Unit = {
    val array2d = Array(
      Array(4, 5, 3),
      Array(30, 20),
      Array(10),
      Array(1, 2, 6, 7, 8)
    )

    val arr = flattenAndSort(array2d)

    // Print result as comma‑separated values
    println(arr.mkString(", "))
  }
}


/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered 2 hours ago by avibootz

Related questions

...