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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to create an M x N matrix with random numbers in Scala

1 Answer

0 votes
import scala.util.Random

object RandomMatrixApp {

  val ROWS = 4
  val COLS = 5

  // Print matrix to console
  def printMatrix(matrix: Array[Array[Int]]): Unit = {
    for (row <- matrix) {
      println(row.map(v => f"$v%4d").mkString)
    }
  }

  // Generate a random integer between min and max inclusive
  def generateRandomInteger(min: Int, max: Int): Int = {
    val rng = new Random()
    rng.nextInt(max - min + 1) + min
  }

  // Generate a rows x cols matrix filled with random integers
  def generateRandomMatrix(rows: Int, cols: Int): Array[Array[Int]] = {
    val rng = new Random()
    Array.tabulate(rows, cols)((_, _) => rng.nextInt(100) + 1)
  }

  def main(args: Array[String]): Unit = {
    val matrix = generateRandomMatrix(ROWS, COLS)

    printMatrix(matrix)
  }
}



/*
run:

  29  35  69  67  80
  30  14  99  94  38
  24  75  27  27  40
   4  22  72  34  41

*/

 



answered Nov 22, 2025 by avibootz
edited Nov 22, 2025 by avibootz
...