Ejemplo n.º 1
0
        private static void DumpBoard(Board board, string header, Cell highlightCell = null)
        {
            Console.WriteLine(header);

            var dump = board.GetDump(highlightCell);
            Console.WriteLine(dump);
        }
        Board s(int num, Board b)
        {
            if (num > 81 || b.checkComplete())
            {
                return b;
            }

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (b.get(i, j) == 0)
                    {
                        for (int n = 1; n < 10; n++)
                        {
                            if (!existInRow(b, j, n) && !existInCol(b, i, n) && !existInZone(b, i, j, n))
                            {
                                int[,] copy = (int[,])b.getArray().Clone();
                                b.set(i, j, n);
                                Board tmp = s(num + 1, b);
                                if (tmp != null)
                                {
                                    return tmp;
                                } else
                                {
                                    b.set(copy);
                                }
                            }
                        }
                        return null;
                    }
                }
            }
            return b;
        }
        private static IEnumerable<Cell> GetColumnPositions(Board board, Cell value, int gx)
        {
            var result =
                from c in board
                where c.Value == value.Value && c.XSection == gx
                select c;

            return result.ToArray();
        }
 bool existInCol(Board b, int x, int val)
 {
     for (int i = 0; i < 9; i++)
     {
         if (b.get(x, i) == val)
         {
             return true;
         }
     }
     return false;
 }
 bool existInRow(Board b, int y, int val)
 {
     for (int i = 0; i < 9; i++)
     {
         if (b.get(i, y) == val)
         {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 6
0
        public static void Play(Board board)
        {
            var strategy = new GameEngine();

            var bestEffort = strategy.Solve(board);
            if (bestEffort.IsSolved())
            {
                Console.WriteLine("SOLVED!");
            }
            else
            {
                Console.WriteLine("UNSOLVED.");
            }
        }
Ejemplo n.º 7
0
        public Board(Board pBoard)
        {
            mPosValues = new bool[9, 9, 10];
             mHeatMap = new int[9, 9];

             for (int i = 0; i < 9; ++i)
            for (int j = 0; j < 9; ++j)
            {
               mHeatMap[i, j] = pBoard.mHeatMap[i, j];
               for (int k = 0; k < 10; ++k)
               {
                  mPosValues[i, j, k] = pBoard.mPosValues[i, j, k];
               }
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Board b = new Board(n);
            StreamReader inputPuzzles;
            Square[] firstThree = new Square[3];
            int sum = 0;
            inputPuzzles = new StreamReader("p096_sudoku.txt");
            String temp, puzzleString;
            for (int currentPuzzle = 0; !inputPuzzles.EndOfStream; currentPuzzle++)
            {
                puzzleString = "";
                temp = "";
                temp = inputPuzzles.ReadLine();
                while (!inputPuzzles.EndOfStream && !temp.StartsWith("G"))
                {
                    puzzleString = puzzleString + temp;
                    temp = inputPuzzles.ReadLine();
                }
                if (puzzleString.Length > n)
                {
                    b = new Board(3);
                    b.setupBoardFromString(puzzleString);

                    //b.showSquares();
                    b.completePuzzle();
                    Console.WriteLine(b.showSquares());
                    temp = "";
                    //Console.WriteLine(b.showSquares());
                    for (int index = 0; index < 3; index++)
                    {
                        if ((b.getSquares()[index].getValue() + 1) == 0)
                        {
                            Console.WriteLine(b.showSquares());
                            break;
                        }
                        temp = temp + (b.getSquares()[index].getValue() + 1);

                    }
                    //Console.WriteLine(temp);
                    sum += int.Parse(temp);
                    //Console.WriteLine(sum);
                    // Console.ReadLine();
                }

            }
            Console.WriteLine(sum);
            Console.ReadLine();
        }
        /*
         * IntersectionStrategy takes it this far:

              9 8
              3 2 7  1 9      8
                5 4    8 2

              7 4    6        9
              2 9
                1 3      7

             >4<       5    2
              5 6      1 4  8 7 3
                            5   4

         * Take it further! (resolve that >4<)
         */
        public Cell Solve(Board board)
        {
            // iterate over all numbers
            foreach (var cellValue in Cell.All)
            {
                // for each sub-grid
                for (var x = 0; x < Board.GridSize; x++)
                {
                    for (var y = 0; y < Board.GridSize; y++)
                    {
                        // and search
                        var values = board.GetGridCells (x,y);
                        if (values.Contains(cellValue))
                        {
                            continue;
                        }

                        // attempt solve this
                        var availablePositions = board
                            .GetGridCells(x, y)
                            .Where(i => !i.IsAssigned())
                            .ToArray();

                        // check columns
                        var adjacentColumnPositions = GetColumnPositions (board, cellValue, x);
                        var adjacentRowPositions =    GetRowPositions (board, cellValue, y);

                        var candidates =
                            availablePositions
                                .ExcludeOn(adjacentColumnPositions, i => i.X)
                                .ExcludeOn(adjacentRowPositions, i => i.Y)
                                .ToArray();

                        if (candidates.Length == 1)
                        {
                            var target = candidates[0];
                            var move = target.Apply(cellValue);
                            Statistics.NeighbouringNumbersStrategyMoves++;
                            return move;
                        }
                    }
                }
            }

            // give up
            return null;
        }
Ejemplo n.º 10
0
        bool existInZone(Board b, int x, int y, int val)
        {
            int[] zonesLimits = new int[] { 0, 0, 0, 3, 3, 3, 6, 6, 6 };

            for (int i = zonesLimits[x]; i < zonesLimits[x] + 3; i++)
            {
                for (int j = zonesLimits[y]; j < zonesLimits[y] + 3; j++)
                {
                    if (b.get(i, j) == val)
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Ejemplo n.º 11
0
        private bool FindSolution(Board board, int index)
        {
            int row = index/SIZE, column = index%SIZE;

            if (index == SIZE*SIZE) return true;

            if (board.IsFilled(row, column))  return FindSolution(board, index+1);

            foreach(int value in board.GetOptionsForCell(row, column))
            {
                board.SetCellValue(row, column, value);
                if (FindSolution(board, index+1)) return true;
            }
            board.ClearCell(row, column);

            return false;
        }
Ejemplo n.º 12
0
        public Board Solve(Board board)
        {
            IStrategy strategy = new OverallStrategy();
            bool success = true;
            Board currentBoard = board;

                    DumpBoard(currentBoard, "Intial board:");

            do
                {
                var move = strategy.Solve(currentBoard);

                success = (move != null);
                if (success)
                {
                    var newBoard = currentBoard.Apply(move);

                // TODO:
                /*
                 * var moves = strategy.GetSolutionSpace(board);
                 * if (moves != null)
                 * {
                 *     newBoard = moves.Aggregate(board, i => i == null : null ? i.Apply);
                 * }
                 */

                // sanity-check
                    var valid = newBoard.Validate();
                    if (!valid)
                {
                        Console.WriteLine("ERROR! Board has been corrupted.");
                        success = false;
                }
                else
                {
                        currentBoard = newBoard;
                        TotalMoves++;
                        string msg = string.Format("Current board (Total {0} moves):", TotalMoves);
                        DumpBoard(currentBoard, msg, move);
                }
            }

            } while (success);

            return currentBoard;
        }
Ejemplo n.º 13
0
        public Cell Solve(Board board)
        {
            // results
            var solutions =
                from c in board
                where !c.IsAssigned()
                let cands = GetValueCandidates(board, c)
                where cands.Length == 1
                let cand = cands.First()
                select c.Apply(cand);

            //var result = solutions.ToArray();
            var result = solutions.FirstOrDefault();
            if (result != null)
            {
                Statistics.IntersectonStrategyMoves ++;
            }
            return result;
        }
Ejemplo n.º 14
0
 private void button1_Click(object sender, RoutedEventArgs e)
 {
     ShowMessage("Solving...",MessageType.Message);
     try
     {
         myboard.StringToInt();
     }
     catch(Exception ex)
     {
         ShowMessage("Invalid Board, Please Check.", MessageType.Failure);
         return;
     }
     original = myboard.DeepClone();
     try
     {
         bool test = myboard.IsValid();
         watch.Start();
         if (!Solve(myboard))
         {
             watch.Stop();
             myboard = original;
             MyBoard.ItemsSource = myboard.StringSpace;
             ShowMessage("Failed to find solution, time: " + watch.Elapsed.TotalSeconds, MessageType.Failure);
         }
         else
         {
             watch.Stop();
             ShowMessage("Solved Already Silly!", MessageType.Warning);
         }
         watch.Reset();
     }
     catch (System.ArgumentException ex)
     {
         MyBoard.ToString();
         MyBoard.ItemsSource = myboard.StringSpace;
         MyBoard.Items.Refresh();
         ShowMessage("Solved in: "+watch.Elapsed.TotalSeconds+ " seconds.",MessageType.Message);
         watch.Stop();
         watch.Reset();
         return;
     }
 }
Ejemplo n.º 15
0
        public Cell Solve(Board board)
        {
            var strategies = new IStrategy[]
            {
                new IntersectionStrategy(),
                new NeighbouringNumbersStrategy(),
                new TentativeStrategy()
            };

            foreach (var strategy in strategies)
            {
                var result = strategy.Solve(board);
                if (result != null)
                {
                    return result;
                }
            }

            return null;
        }
Ejemplo n.º 16
0
        public static Cell[] GetValueCandidates(Board board, Cell cell)
        {
            var columnValues = board.GetAssignedColumnCells(cell);
            var rowValues =    board.GetAssignedRowCells(cell);
            var gridValues = board.GetGridCells(cell)
                .Where(i => i.IsAssigned())
                .ToArray();

            var all = Cell.All;
            // BUG: "all" keeps bad positional value, corrupting board.

            var missingColumnValues = all.Except(columnValues).ToArray();
            var missingRowValues =    all.Except(rowValues)   .ToArray();
            var missingGridValues =   all.Except(gridValues)  .ToArray();

            var candidates = missingColumnValues
                .Intersect(missingRowValues)
                .Intersect(missingGridValues)
                .ToArray();

            return candidates;
        }
Ejemplo n.º 17
0
 private void button2_Click(object sender, RoutedEventArgs e)
 {
     myboard = new Board();
     MyBoard.ItemsSource = myboard.StringSpace;
     ShowMessage("Board Reset",MessageType.Message);
 }
Ejemplo n.º 18
0
 bool SolveComplete(Board board)
 {
     List<Board> sucessors = new System.Collections.Generic.List<Board>();
     for (int i = 0; i < 9; i++)
     {
         for (int j = 0; j < 9; j++)
         {
             if (board.spaces[i][j] == 0)
             {
                 for (int r = 1; r < 10; r++)
                 {
                     board.SetSpace(r, i, j);
                     if (board.IsSolved(i, j))
                     {
                         watch.Stop();
                         Solved++;
                         return true;
                     }
                     if (board.IsValid(i,j))
                     {
                         sucessors.Add(board.DeepClone());
                     }
                 }
                 foreach (Board brd in sucessors)
                 {
                     SolveComplete(brd);
                 }
                 return false;
             }
         }
     }
     if (myboard.IsValid())
     {
         return true;
     }
     return false;
 }
Ejemplo n.º 19
0
 public Solver(Board board)
 {
     this.board = board;
 }
Ejemplo n.º 20
0
 private bool Generate(Board board)
 {
     List<Board> sucessors = new System.Collections.Generic.List<Board>();
     for (int i = 0; i < 9; i++)
     {
         for (int j = 0; j < 9; j++)
         {
             if (board.spaces[i][j] == 0)
             {
                 Random rand = new Random();
                 List<int> nums = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                 while(nums.Count!=0)
                 {
                     int r = nums[rand.Next(0,nums.Count)];
                     nums.Remove(r);
                     board.SetSpace(r, i, j);
                     if (board.IsValid())
                     {
                         sucessors.Add(board.DeepClone());
                         if (board.IsSolved(i, j))
                         {
                             watch.Stop();
                             myboard = board.DeepClone();
                             throw new System.ArgumentException("Solved");
                         }
                     }
                 }
                 foreach (Board brd in sucessors)
                 {
                     Generate(brd);
                 }
             }
         }
     }
     if (myboard.IsValid())
     {
         return true;
     }
     return false;
 }
Ejemplo n.º 21
0
 private void RemoveSpaces(Board board)
 {
     List<Tuple<int, int>> Spaces = new List<Tuple<int, int>>();
     for (int i = 0; i < 9; i++)
     {
         for (int j = 0; j < 9; j++)
         {
             Spaces.Add(new Tuple<int, int>(i, j));
         }
     }
     Random rand = new Random();
     for (int i = 0; i < 81; i++)
     {
         int index = rand.Next(0, Spaces.Count);
         if (board.spaces[Spaces[index].Item1][Spaces[index].Item2] != 0)
         {
             int temp = board.spaces[Spaces[index].Item1][Spaces[index].Item2];
             board.spaces[Spaces[index].Item1][Spaces[index].Item2] = 0;
             Removed++;
             Solved = 0;
             SolveComplete(board.DeepClone());
             if (Solved == 1)
             {
             }
             if (Solved == 1 && Removed >= 50)
             {
                 myboard = board.DeepClone();
                 throw new System.ArgumentException("Generated");
             }
             else if (Solved == 1 && Removed < 50)
             {
                 RemoveSpaces(board.DeepClone());
             }
             board.spaces[Spaces[index].Item1][Spaces[index].Item2] = temp;
             Removed--;
         }
         Spaces.RemoveAt(index);
     }
 }
        static void Main(string[] args)
        {
            // Initialise board
            Board b = new Board();
            b.set(new int[,] {
                { 0,1,4, 2,0,0, 0,9,0},
                { 0,2,0, 0,0,0, 0,0,3},
                { 0,6,5, 0,8,0, 0,4,0},

                { 0,0,8, 0,3,0, 0,0,0},
                { 2,0,0, 5,0,7, 0,0,8},
                { 0,0,0, 0,4,0, 6,0,0},

                { 0,8,0, 0,2,0, 1,6,0},
                { 4,0,0, 0,0,0, 0,5,0},
                { 0,7,0, 0,0,5, 9,8,0} });
            //b.set(new int[,] {
            //    { 0,0,0, 0,0,0, 0,0,0},
            //    { 0,0,0, 0,0,0, 0,0,0},
            //    { 0,0,0, 0,0,0, 0,0,0},

            //    { 0,0,0, 0,0,0, 0,0,0},
            //    { 0,0,0, 0,0,0, 0,0,0},
            //    { 0,0,0, 0,0,0, 0,0,0},

            //    { 0,0,0, 0,0,0, 0,0,0},
            //    { 0,0,0, 0,0,0, 0,0,0},
            //    { 0,0,0, 0,0,0, 0,0,0} });
            //b.set(new int[,]
            //{
            //    { 0,6,1, 2,0,8, 3,0,9},
            //    { 0,0,0, 0,0,1, 4,0,2},
            //    { 0,0,2, 0,0,0, 6,0,0},

            //    { 6,2,0, 0,5,3, 0,0,4},
            //    { 5,0,0, 0,8,0, 0,0,6},
            //    { 1,0,0, 6,2,0, 0,7,3},

            //    { 0,0,4, 0,0,0, 7,0,0},
            //    { 8,0,6, 3,0,0, 0,0,0},
            //    { 3,0,5, 7,0,2, 9,6,0}
            //});

            // Ask user for input
            string input = "";
            int x = 0, y = 0, value = 0;
            string[] split;

            while (true)
            {
                Console.Clear();
                b.render();
                Console.WriteLine("Enter data in the format [x y value], or enter 0 to solve: ");
                input = Console.ReadLine();

                split = input.Split(' ');
                if (split.Length == 3)
                {
                    x = Int32.Parse(split[0]);
                    y = Int32.Parse(split[1]);
                    value = Int32.Parse(split[2]);

                    b.set(x, y, value);
                } else if (input == "0")
                {
                    break;
                }
            }

            // Attempt to solve sudoku
            Solver s = new Solver(b.copy());

            Stopwatch watch = new Stopwatch();

            watch.Start();
            Board result = s.solve();
            watch.Stop();

            // Check complete
            if (result == null || !result.checkComplete())
            {
                Console.WriteLine(":( Unable to solve.");
            }
            else
            {
                Console.Clear();
                b.render();
                Console.WriteLine("Solved! Time used " + watch.Elapsed.TotalMilliseconds + "ms. Here it is: ");
                result.render();
            }
        }
Ejemplo n.º 23
0
 private void button3_Click(object sender, RoutedEventArgs e)
 {
     Removed = 0;
     Solved = 0;
     myboard = new Board();
     try
     {
         Generate(myboard);
     }
     catch (System.ArgumentException ex)
     {
         try
         {
             RemoveSpaces(myboard);
         }
         catch (System.ArgumentException ex2)
         {
             myboard.IntToString();
             MyBoard.ItemsSource = myboard.StringSpace;
         }
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Main create a board and tries to solve it
        /// </summary>
        /// <param name="args">Filename from the command line</param>
        public static void Main(string[] args)
        {
            if (args.Length > 0)
             {
            Board iniBoard = new Board(args[0]);

            //            System.Console.WriteLine(iniBoard);

            if(solve(iniBoard) && !checkCompleteness(iniBoard))
            {
               iniBoard = backTrack(iniBoard);
            }

            if (iniBoard != null)
               System.Console.Write(iniBoard);
            else
               System.Console.Write("Board is unsolvable");

            //            System.Console.Read();
             }
             else
             {
            System.Console.WriteLine("Requires a file to read from");
             }
        }
Ejemplo n.º 25
0
        private void Guess()
        {
            //find a square with two possible values
            Console.WriteLine("Guessing!");
            Square[] temp;
            Board branch;
            List<Square[]> permutations = new List<Square[]>();
            for (int i = 0; i < n4; i++)
            {
                if (allSquares[i].getValue() != Square.NULL_VALUE)
                {

                    foreach (int values in allSquares[i].GetPossibleValuesList())
                    {
                        temp = new Square[n4];
                        Array.Copy(allSquares, temp, n4);
                        temp[i].setValue(i);
                        permutations.Add(temp);
                    }
                }
            }
            foreach (Square[] sArr in permutations)
            {
                branch = new Board(n, sArr);
                branch.completePuzzle();
                if (branch.isLegal() && branch.isComplete())
                {
                    allSquares = branch.allSquares;
                    Console.WriteLine(showSquares() + "\n\n!!!!!!!");
                    Console.ReadLine();
                }

            }
        }
Ejemplo n.º 26
0
        private static Board backTrack(Board pBoard)
        {
            int coolestNode = pBoard.getLowestHeat();
             int row = coolestNode / 9;
             int col = coolestNode % 9;
             Board copy = null;

             for (int i = 1; i < 10; ++i)
             {
            copy = pBoard.getCopy();
            i = copy.getFirstVal(row, col, i);

            /*            System.Console.WriteLine(copy);
            System.Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++\n" +
                                     "row=" + row + " col=" + col + "val=" + i +
                                     "\n+++++++++++++++++++++++++++++++++++++++++++++\n");
            System.Console.Read();*/

            if (i < 10 && copy.update(row, col, i) && solve(copy))
               if (checkCompleteness(copy))
                  return copy;
               else
               {
                  copy = backTrack(copy);
                  if (copy != null && checkCompleteness(copy))
                     return copy;
               }
             }

             return null;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// We want to know if we found a partial or complete solution
        /// </summary>
        /// <param name="pBoard">Board to check</param>
        /// <returns>Whether the Board is complete</returns>
        private static bool checkCompleteness(Board pBoard)
        {
            bool complete = true;

             for (int i = 0; i < 9 && complete; ++i)
            for (int j = 0; j < 9 && complete; ++j)
            {
               //The board is not complete if there is ever more than one possible value
               if (pBoard.getHeat(i, j) > 1)
                  complete = false;
            }

             return complete;
        }
Ejemplo n.º 28
0
 public Solver(Board board)
 {
     b = board;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Attempts to solve the board
        /// </summary>
        /// <param name="pBoard">Board to be solved</param>
        /// <returns>Whether or not the board given is valid</returns>
        private static bool solve(Board pBoard)
        {
            bool update;
             bool valid = true;

             do
             {
            update = false;
            for (int i = 0; valid && i < 9; ++i)
               for (int j = 0; valid && j < 9; ++j)
               {
                  //If there is only one option and it's not already locked in
                  if (pBoard.getHeat(i, j) == 1 && !pBoard.isLocked(i, j))
                  {
                     update = true;
                     //Update the board
                     valid = pBoard.update(i, j, pBoard.getFirstVal(i, j));
                  }
               }
             }
             while(update && valid);

             return valid;
        }
Ejemplo n.º 30
0
 public Board getCopy()
 {
     Board copy = new Board(this);
      return copy;
 }