diff --git a/PuzzlePlayer/Binary.cs b/PuzzlePlayer/Binary.cs index 385aa0c30b273f8b2d312fb20b96a88523315644..a7162177b9471c6332253ea1eac8375ecd05c68c 100644 --- a/PuzzlePlayer/Binary.cs +++ b/PuzzlePlayer/Binary.cs @@ -101,22 +101,29 @@ namespace PuzzlePlayer_Namespace boardState = (int[,])generatedBoard.Clone(); + // generate a list with all positions + List<(int,int)> allPositions = new List<(int,int)> (); + for(int i = 0; i < boardState.GetLength(0); i++) + for(int j = 0; j < boardState.GetLength(1); j++) + allPositions.Add(new (i, j)); Random rnd = new Random(); //remove spaces until the board is unsolvable, then go one step back while (true) { - int[,] copy = (int[,])boardState.Clone(); - int x = rnd.Next(boardState.GetLength(0)); - int y = rnd.Next(boardState.GetLength(1)); + if(allPositions.Count == 0) + break; - if (boardState[x,y] != emptySpace) - boardState[x,y] = emptySpace; + int i = rnd.Next(allPositions.Count); + (int x, int y) = allPositions[i]; + int copy = boardState[x,y]; // create a copy in case it is not possible to solve the puzzle anymore + + boardState[x,y] = emptySpace; + allPositions.RemoveAt(i); if(Solve(true) == SOLUTIONS.NONE) { - boardState = (int[,])copy.Clone(); - break; + boardState[x, y] = copy; // restore the copy if there are no solutions found } } // save the generated board for testing the users solution and the use of a reset button