Permalink
Browse files

add 8queens

  • Loading branch information...
1 parent 1652055 commit 9671e07d031901b0bc60eccaab7aa29782909de1 @miekg committed Sep 24, 2012
Showing with 69 additions and 0 deletions.
  1. +11 −0 ex-functions/ex-queen8.tex
  2. +58 −0 ex-functions/src/queen8.go
View
@@ -0,0 +1,11 @@
+\begin{Exercise}[title={Eight Queens Puzzle},difficulty=2]
+\label{ex:queen8}
+\Question\label{ex:queen8 q1}
+%%http://en.wikipedia.org/wiki/Eight_queens_puzzle
+\end{Exercise}
+
+\begin{Answer}
+\Question The following function calculates the average:
+\lstinputlisting[caption=Average function in Go,linerange={3,14}]{ex-functions/src/ave.go}
+\showremarks
+\end{Answer}
View
@@ -0,0 +1,58 @@
+package main
+
+import (
+ "fmt"
+)
+
+const (
+ size = 8
+ norm = size - 1
+)
+
+var B = [size][size]string{
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."},
+ {".", ".", ".", ".", ".", ".", ".", "."}}
+
+var leftdiag [size*2 - 1]bool
+var rightdiag [size*2 - 1]bool
+var col [size]bool
+
+func main() {
+ tryQueen(0)
+}
+
+func tryQueen(x int) {
+ for y := 0; y < size; y++ {
+ if col[y] == false && leftdiag[x-y+norm] == false && rightdiag[x+y] == false {
+ B[y][x] = "Q" // reverse coordinates so it prints correctly
+ col[y] = true
+ leftdiag[x-y+norm] = true
+ rightdiag[x+y] = true
+ if x < size-1 {
+ tryQueen(x + 1)
+ } else {
+ fmt.Printf("Solution found\n%s", func() string {
+ s := ""
+ for i := 0; i < 8; i++ {
+ for j := 0; j < 8; j++ {
+ s += B[i][j]
+ }
+ s += "\n"
+ }
+ return s
+ }())
+ return
+ }
+ B[y][x] = "."
+ col[y] = false
+ leftdiag[x-y+norm] = false
+ rightdiag[x+y] = false
+ }
+ }
+}

0 comments on commit 9671e07

Please sign in to comment.