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 Go

1 Answer

0 votes
package main

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

import (
    "fmt"
    "math/rand"
    "time"
)

// Function to shuffle an array
func shuffleArray(arr []int) {
    rand.Seed(time.Now().UnixNano())
    for i := len(arr) - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        arr[i], arr[j] = arr[j], arr[i]
    }
}

// Function to fill the Sudoku grid
func fillSudokuGrid() [][]int {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}

    // Shuffle the numbers randomly
    shuffleArray(numbers)

    // Fill the 3x3 grid row by row
    grid := make([][]int, 3)
    for i := range grid {
        grid[i] = make([]int, 3)
    }

    index := 0
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            grid[i][j] = numbers[index]
            index++
        }
    }
    return grid
}

// Function to print the grid
func printGrid(grid [][]int) {
    for _, row := range grid {
        for _, num := range row {
            fmt.Printf("%d ", num)
        }
        fmt.Println()
    }
}

func main() {
    // Initialize and fill the 3x3 grid
    grid := fillSudokuGrid()

    // Print the grid
    fmt.Println("Generated 3x3 Sudoku Grid:")
    printGrid(grid)
}

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

*/

 



answered Jun 1, 2025 by avibootz

Related questions

...