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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,140 questions

56,014 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

...