This project involves writing a computer program to solve the “peg puzzle”, which is a puzzle something like this:
In this puzzle, you start with pegs in each hole of the board except for one. Each turn, you can move a peg in a straight line over exactly one other peg to land in a hole, and then remove the peg that was jumped over. The goal is to end with only one peg remaining, and in particular, to end with that one remaining peg in a particular location.
The puzzle could in theory have different sizes. We will denote puzzle size by N to represent the number of rows. For example, for the above puzzle, N = 5.
In order to represent the state of the puzzle, we can define a State class to capture the puzzle state.
We shall store in this state a two-dimensional array of flags for whether there is a peg present in a given location of the puzzle. For example, assuming the puzzle starts out with pegs in each hole except the top hole, we have a state that looks like:
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 0 | ||||
| 1 | 1 | 1 | |||
| 2 | 1 | 1 | 1 | ||
| 3 | 1 | 1 | 1 | 1 | |
| 4 | 1 | 1 | 1 | 1 | 1 |
There are six possible movement directions:
A peg position is valid iff:
We can first write a brute-force algorithm to look for all solutions to the puzzle following an algorithm something like this:
This will evaluate every possible game.
If we are looking for solutions that end in a particular end state, we can also use a reverse algorithm starting with a desired ending board state (for example, one peg left in the top position):