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 Swift

1 Answer

0 votes
import Foundation

// 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.

func fillSudokuGrid() -> [[Int]] {
    var numbers = Array(1...9)

    // Shuffle the numbers randomly
    numbers.shuffle()

    // Initialize a 3x3 grid
    var grid = Array(repeating: Array(repeating: 0, count: 3), count: 3)
    var index = 0

    for i in 0..<3 {
        for j in 0..<3 {
            grid[i][j] = numbers[index]
            index += 1
        }
    }
    return grid
}

func printGrid(_ grid: [[Int]]) {
    for row in grid {
        print(row.map { String($0) }.joined(separator: " "))
    }
}

let grid = fillSudokuGrid()
print("Generated 3x3 Sudoku Grid:")
printGrid(grid)

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

*/

 



answered Jun 1, 2025 by avibootz

Related questions

...