From 55b0a16b2906cb180dad7555e0098d0b40e721e5 Mon Sep 17 00:00:00 2001
From: bionic85 <144353436+bionic85@users.noreply.github.com>
Date: Mon, 2 Dec 2024 18:38:52 +0100
Subject: [PATCH] binary generator is nu echt helemaal done

---
 PuzzlePlayer/Binary.cs | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/PuzzlePlayer/Binary.cs b/PuzzlePlayer/Binary.cs
index 385aa0c..a716217 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
-- 
GitLab