1 // $G $F.go && $L $F.$A # don't run it - produces too much output
3 // Copyright 2010 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 // This program solves the (English) peg solitaire board game.
8 // See also: http://en.wikipedia.org/wiki/Peg_solitaire
12 const N = 11 + 1 // length of a board row (+1 for newline)
14 // The board must be surrounded by 2 illegal fields in each direction
15 // so that move() doesn't need to check the board boundaries. Periods
16 // represent illegal fields, ● are pegs, and ○ are holes.
32 // center is the position of the center hole if there is a single one;
33 // otherwise it is -1.
38 for pos, field := range board {
45 center = -1 // no single hole
50 var moves int // number of times move is called
52 // move tests if there is a peg at position pos that can jump over another peg
53 // in direction dir. If the move is valid, it is executed and move returns true.
54 // Otherwise, move returns false.
55 func move(pos, dir int) bool {
57 if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {
60 board[pos+2*dir] = '●'
67 // unmove reverts a previously executed valid move.
68 func unmove(pos, dir int) {
71 board[pos+2*dir] = '○'
75 // solve tries to find a sequence of moves such that there is only one peg left
76 // at the end; if center is >= 0, that last peg must be in the center position.
77 // If a solution is found, solve prints the board after each move in a backward
78 // fashion (i.e., the last board position is printed first, all the way back to
79 // the starting board position).
82 for pos, field := range board {
83 // try each board position
86 for _, dir := range [...]int{-1, -N, +1, +N} {
89 // a valid move was found and executed,
90 // see if this new board has a solution
93 println(string(board))
103 // tried each possible move
104 if n == 1 && (center < 0 || last == center) {
105 // there's only one peg left
106 println(string(board))
109 // no solution found for this board
116 println("no solution found")
118 println(moves, "moves tried")