private void SolveRecursive(IProblem problem, Board initial, Board board, IAssignmentCollection assignments) { var availableAssignments = problem.GetDomains(board).ToList(); // if there's no more assignments the game is done, save, then go back up the chain if (availableAssignments.Count == 0) { solutions.Add(new Solution(initial, assignments)); return; } foreach (var assignment in availableAssignments) { // keep a list of visited nodes. if we've seen this // before then skip it, no need to explore it again string hashCode = assignment.Board.ToString(false); if (visitedNodes.Contains(hashCode)) continue; else visitedNodes.Add(hashCode); // add assignment to previous lsit var newAssignments = assignments.Clone(); newAssignments.Add(assignment); // recurse down recursionLevel++; SolveRecursive(problem, initial, assignment.Board, newAssignments); recursionLevel--; } }
public Solution(Board initialState, IEnumerable<Assignment> assignments) { Check.Require(initialState != null, "initialState is a required argument."); Check.Require(assignments != null, "assignments is a required argument."); InitialState = initialState; Assignments = new ReadOnlyCollection<Assignment>(assignments.ToList()); FinalState = Assignments.Last().Board; PegCount = FinalState.PegCount; Depth = Assignments.Count; }
public virtual IEnumerable<Assignment> GetDomains(Board board) { var assignments = new List<Assignment>(); var pegSpaces = board.GetSpacesWithPegs(); foreach (var peg in pegSpaces) { var jumps = GetAvailableJumps(board, peg); if (jumps.Count > 0) assignments.AddRange(jumps.Select(jump => new Assignment(board.ExecuteJump(jump), jump))); } return assignments; }
private List<Jump> GetAvailableJumps(Board board, Coordinate peg) { List<Jump> jumps = new List<Jump>(); // check each direction for (int i = 0; i < xs.Length; i++) { var jumped = new Coordinate(peg.X + (xs[i] * 1), peg.Y + (ys[i] * 1)); var target = new Coordinate(peg.X + (xs[i] * 2), peg.Y + (ys[i] * 2)); // check that the next coord over and the one after that exist // and that next has a peg to jump and the one after is empty if (board.ContainsCoordinate(jumped) && board.ContainsCoordinate(target) && board[jumped].HasPeg == true && board[target].HasPeg == false) jumps.Add(new Jump(peg, jumped, target)); } return jumps; }
/// <summary> /// Returns true if the boards have the same positions /// and peg value. Otherwise false. /// </summary> /// <param name="board">The board to compare to this one.</param> /// <returns>True if equivalent, otherwise false.</returns> public bool IsEquivalent(Board board) { Check.Require(board != null, "board is a required argument and cannot be null."); if (this.Rank != board.Rank) return false; for (int i = 0; i < spaces.Length; i++) { if (spaces[i] != board.spaces[i] || spaces[i].HasPeg != board.spaces[i].HasPeg) return false; } return true; }