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,907 questions

51,839 answers

573 users

How to fill a 3x3 grid to be a valid Sudoku grid in Scala

1 Answer

0 votes
import scala.util.Random

// To fill a 3x3 grid to be a valid Sudoku grid, you must ensure that each row, 
// column, and the 3x3 grid contains the numbers 1 through 9 without repetition.

object SudokuGridGenerator {
  val Size = 3

  // Function to shuffle an array
  def shuffleArray(arr: Array[Int]): Array[Int] = {
    val shuffled = arr.clone()
    Random.shuffle(shuffled.toSeq).toArray
  }

  // Function to fill the Sudoku grid
  def fillSudokuGrid(): Array[Array[Int]] = {
    val numbers = (1 to 9).toArray

    // Shuffle the numbers randomly
    val shuffledNumbers = shuffleArray(numbers)

    // Fill the 3x3 grid row by row
    val grid = Array.ofDim[Int](Size, Size)
    var index = 0

    for (i <- 0 until Size; j <- 0 until Size) {
      grid(i)(j) = shuffledNumbers(index)
      index += 1
    }
    grid
  }

  // Function to print the grid
  def printGrid(grid: Array[Array[Int]]): Unit = {
    grid.foreach(row => println(row.mkString(" ")))
  }

  def main(args: Array[String]): Unit = {
    val grid = fillSudokuGrid()
    
    println("Generated 3x3 Sudoku Grid:")
    printGrid(grid)
  }
}


 
/*
run:

Generated 3x3 Sudoku Grid:
7 9 5
3 8 2
6 4 1

*/

 



answered Jun 1, 2025 by avibootz

Related questions

...