Wrote a simple program for codingame.com. It works.
Tried to change the output to print a string instead of individual bytes. The compiler doesn’t like it.
Compiler error message:
./Answer.go:80: cannot convert outes[i] (type [4]byte) to type string
Program:
// Mini Sudoku solver - solves a 4×4 sudoku grid that has only one solution.
package main
import "fmt"
func onebit(v uint8) int { // if only one bit is set, return its position
n := 1 // otherwise return 0
for (v>0) {
v >>= 1
if (v & 1)==1 {
if v==1 { return n
} else { return 0
}
}
n++
}
return 0
}
func main() {
var lines[4] string
var block[4][4] byte
var outes[4][4] byte
for i:=range lines { // Read input, prep worksheets
fmt.Scan(&lines[i])
for j:=range block[0] {
outes[i][j] = lines[i][j]
block[i][j] = 0x1e
}
}
flag := 1
for flag>0 {
flag = 0
for i:=range block { // eliminate possibilites
for j:=range block[0] {
if outes[i][j] != '0' {
mask := uint8(^(1 << (outes[i][j] - '0')))
for k:=range block[0] {
block[i][k] &= mask // by row
}
for k:=range block {
block[k][j] &= mask // by column
}
startx := j & 2;
starty := i & 2
for k:=starty; k<starty+2; k++ { // by subblock
for m:=startx; m<startx+2; m++ {
block[k][m] &= mask
}
}
}
}
}
for i:=range block { // scan for single possible value
for j:=range block[0] {
if outes[i][j] == '0' {
n := onebit(block[i][j])
if n>0 {
outes[i][j] = byte(n + '0') // add to solution
} else {
flag = 1
}
}
}
}
}
/*
for i:=range outes {
for j:=range outes[0] {
fmt.Printf("%c", outes[i][j])
}
fmt.Println()
}
*/
for i:=range outes {
fmt.Printf("%s\n", string(outes[i]))
}
}