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 // Test general operation by solving a peg solitaire game.
8 // A version of this is in the Go playground.
9 // Don't run it - produces too much output.
11 // This program solves the (English) peg solitaire board game.
12 // See also: http://en.wikipedia.org/wiki/Peg_solitaire
16 const N = 11 + 1 // length of a board row (+1 for newline)
18 // The board must be surrounded by 2 illegal fields in each direction
19 // so that move() doesn't need to check the board boundaries. Periods
20 // represent illegal fields, ● are pegs, and ○ are holes.
35 // center is the position of the center hole if there is a single one;
36 // otherwise it is -1.
41 for pos, field := range board {
48 center = -1 // no single hole
52 var moves int // number of times move is called
54 // move tests if there is a peg at position pos that can jump over another peg
55 // in direction dir. If the move is valid, it is executed and move returns true.
56 // Otherwise, move returns false.
57 func move(pos, dir int) bool {
59 if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {
62 board[pos+2*dir] = '●'
68 // unmove reverts a previously executed valid move.
69 func unmove(pos, dir int) {
72 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
115 println("no solution found")
117 println(moves, "moves tried")