Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code #163

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions board.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import "fmt"

const END_OF_GRID cell = 81

type cell uint8

type grid [][]int

func (c cell) row() int {
return int(c) / 9
}

func (c cell) column() int {
return int(c) % 9
}

func (c cell) String() string {
return fmt.Sprintf("(%d, %d)", c.row(), c.column())
}

func (c cell) next() cell {
if c >= END_OF_GRID {
panic("next() called on cell greater than END_OF_GRID")
}

return c + 1
}

func (g grid) At(c cell) int {
return g[c.row()][c.column()]
}

func (g grid) Set(c cell, v int) {
g[c.row()][c.column()] = v
}

func (g grid) Reset(c cell) {
g[c.row()][c.column()] = 0
}
59 changes: 59 additions & 0 deletions sudoku.go
Original file line number Diff line number Diff line change
@@ -1 +1,60 @@
package main

func isMappingValid(g grid, c cell, newValue int) bool {
// Check row and column
for i := 0; i < 9; i++ {
if g[c.row()][i] == newValue || g[i][c.column()] == newValue {
return false
}
}

// Check box
boxRow := c.row() / 3 * 3
boxColumn := c.column() / 3 * 3
for i := boxRow; i < boxRow + 3; i++ {
for j := boxColumn; j < boxColumn + 3; j++ {
if i == c.row() || j == c.column() { // row and column already checked, so skip
continue
}

if g[i][j] == newValue {
return false
}
}
}

return true
}

func SolveSudokuRecursive(inputGrid grid, c cell) (solvedGrid [][]int) {
if c == END_OF_GRID {
return Copy(inputGrid)
}

if inputGrid.At(c) != 0 {
return SolveSudokuRecursive(inputGrid, c.next())
}

for i := 1; i <= 9; i++ {
if !isMappingValid(inputGrid, c, i) {
continue
}

inputGrid.Set(c, i)
solveChild := SolveSudokuRecursive(inputGrid, c.next())
inputGrid.Reset(c)

if solveChild != nil {
return solveChild
}
}

return nil
}

func SolveSudoku(inputGrid grid) (solvedGrid [][]int) {
return SolveSudokuRecursive(inputGrid, 0)
}

func main() {
}
15 changes: 15 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

func Copy[T any](s [][]T) [][]T {
copy := make([][]T, len(s))

for i := 0; i < len(s); i++ {
copy[i] = make([]T, len(s[i]))

for j, v := range s[i] {
copy[i][j] = v
}
}

return copy
}