Skip to content

Instantly share code, notes, and snippets.

@nouse
Last active May 24, 2016 01:39
Show Gist options
  • Save nouse/9f5e1de7f5c1ea0faea795d59c8ee358 to your computer and use it in GitHub Desktop.
Save nouse/9f5e1de7f5c1ea0faea795d59c8ee358 to your computer and use it in GitHub Desktop.
8 queens puzzle in Go
package main
import (
"bytes"
"fmt"
"math/rand"
"os"
"time"
)
type Queens []int
func (queens Queens) Choices() []int {
currentLayer := len(queens)
result := [8]int{}
for i := 0; i < 8; i++ {
result[i] = i
}
for i, c := range queens {
result[c] = -1
a := c + currentLayer - i
if a >= 0 && a < 8 {
result[a] = -1
}
b := c - currentLayer + i
if b >= 0 && b < 8 {
result[b] = -1
}
}
final := []int{}
for _, r := range result {
if r != -1 {
final = append(final, r)
}
}
return final
}
// Iter to next layer
func Iter(queenList []Queens) []Queens {
final := []Queens{}
for _, queens := range queenList {
for _, c := range queens.Choices() {
q := make([]int, len(queens))
copy(q, queens)
final = append(final, append(q, c))
}
}
return final
}
func main() {
queensList := []Queens{[]int{}}
for i := 0; i < 8; i++ {
queensList = Iter(queensList)
}
fmt.Printf("Total: %d\n", len(queensList))
fmt.Printf("%v\n", queensList)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
queens := queensList[r.Intn(len(queensList))]
buf := new(bytes.Buffer)
strings := "oooooooo"
for _, q := range queens {
buf.WriteString(strings[0:q])
buf.WriteString("x")
buf.WriteString(strings[q:])
buf.WriteString("\n")
}
buf.WriteTo(os.Stdout)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment