How to randomly place a random value in each row of an 8x8 int list with zero values in Scala

1 Answer

0 votes
import scala.util.Random

/*
 * This program creates an 8x8 integer board.
 * For each row:
 *   - All values are set to zero
 *   - One random column is chosen
 *   - A random value (1..100) is placed in that column
 *
 * It mirrors the structure of the C++ version:
 *   initializeBoard()
 *   printBoard()
 *   main()
 */

object RandomBoard {

  val BoardSize: Int = 8

  /*
   * initializeBoard:
   *   - Sets all values to zero
   *   - For each row:
   *       * randomly selects one column (0..7)
   *       * places a random integer (1..100) in that column
   */
  def initializeBoard(board: Array[Array[Int]]): Unit = {
    val rng: Random = new Random()

    for (row <- 0 until BoardSize) {

      // Set entire row to zero
      for (col <- 0 until BoardSize) {
        board(row)(col) = 0
      }

      // Choose a random column index
      val randomCol: Int = rng.nextInt(BoardSize)

      // Place a random non-zero value (1..100)
      val randomValue: Int = rng.nextInt(100) + 1

      board(row)(randomCol) = randomValue
    }
  }

  /*
   * printBoard:
   *   - Prints the 8x8 board in a readable grid format
   */
  def printBoard(board: Array[Array[Int]]): Unit = {
    for (row <- board) {
      println(row.mkString(" "))
    }
  }

  def main(args: Array[String]): Unit = {
    val board: Array[Array[Int]] =
      Array.fill(BoardSize, BoardSize)(0)

    initializeBoard(board)
    printBoard(board)
  }
}


/*
run:

0 0 0 67 0 0 0 0
0 0 0 71 0 0 0 0
0 0 92 0 0 0 0 0
0 0 0 39 0 0 0 0
0 0 0 0 19 0 0 0
29 0 0 0 0 0 0 0
0 0 0 0 0 0 92 0
0 0 62 0 0 0 0 0

*/

 



answered 1 day ago by avibootz

Related questions

...