示例#1
0
        static void Main(string[] args)
        {
            string dir   = args.First();
            var    files = Directory.EnumerateFiles(dir).Where(file => file.EndsWith(".txt", true, CultureInfo.InvariantCulture));

            foreach (string file in files)
            {
                string outputString = "";
                try
                {
                    SudokuBoard  board  = new SudokuBoard(9);
                    SudokuParser parser = new SudokuParser();
                    parser.ParserText(File.ReadAllText(file), board);
                    SudokuSolver solver = new SudokuSolver();
                    solver.SolvePuzzle(board);
                    file.Substring(0, file.Length - 4);
                    outputString = board.ToString();
                }
                catch (Exception e) when((e is ParseException) || (e is SolveException))
                {
                    outputString = e.Message;
                }
                File.WriteAllText($"{file.Substring(0,file.Length-4)}.sln.txt", outputString);
            }
        }
示例#2
0
文件: Program.cs 项目: bobmatt/Sudoku
        static void Main(string[] args)
        {
            // Traditional 9x9 sudoku
            SudokuSolver solver = new SudokuSolver("C:\\SudokuData\\sudoku1.txt");
            var result = solver.SolvePuzzle();
            var validAnswer = solver.ValidatePuzzle("C:\\SudokuData\\sudoku1_answer.txt");
            MessageBox.Show("Puzzle solved:  " + result.ToString() + "\n" +
                "Result valid:  " + validAnswer.ToString() + "\n\n" +
                solver.PuzzleText());

            // 4x4 sudoku
            solver = new SudokuSolver("C:\\SudokuData\\sudoku2.txt");
            result = solver.SolvePuzzle();
            validAnswer = solver.ValidatePuzzle("C:\\SudokuData\\sudoku2_answer.txt");
            MessageBox.Show("Puzzle solved:  " + result.ToString() + "\n" +
                "Result valid:  " + validAnswer.ToString() + "\n\n" +
                solver.PuzzleText());

            // 16x16 sudoku
            solver = new SudokuSolver("C:\\SudokuData\\sudoku3.txt");
            result = solver.SolvePuzzle();
            validAnswer = solver.ValidatePuzzle("C:\\SudokuData\\sudoku3_answer.txt");
            MessageBox.Show("Puzzle solved:  " + result.ToString() + "\n" +
                "Result valid:  " + validAnswer.ToString() + "\n\n" +
                solver.PuzzleText());
        }
示例#3
0
        public void testSolvePuzzle()
        {
            //TODO: More test cases!

            // A solvable puzzle
            int[,] puzzle = {{9,0,0,8,4,0,3,7,0},
                             {1,3,7,0,0,0,0,0,2},
                             {0,0,0,3,0,0,6,0,9},
                             {0,7,0,1,0,8,0,3,6},
                             {0,0,8,0,0,0,7,0,0},
                             {6,4,0,7,0,9,0,5,0},
                             {8,0,3,0,0,5,0,0,0},
                             {4,0,0,0,0,0,9,2,3},
                             {0,2,6,0,1,3,0,0,4}};

            int[,] answer = {{9,6,2,8,4,1,3,7,5},
                             {1,3,7,5,9,6,8,4,2},
                             {5,8,4,3,7,2,6,1,9},
                             {2,7,9,1,5,8,4,3,6},
                             {3,5,8,2,6,4,7,9,1},
                             {6,4,1,7,3,9,2,5,8},
                             {8,9,3,4,2,5,1,6,7},
                             {4,1,5,6,8,7,9,2,3},
                             {7,2,6,9,1,3,5,8,4}};

            //Sudoku. puzzle;
            SudokuSolver solver = new SudokuSolver(puzzle);
            bool result = solver.SolvePuzzle();
            Assert.IsTrue(result);
        }
示例#4
0
        static void Main(string[] args)
        {
            SudokuFieldProvider sudokuFieldProvider = SudokuFieldProvider.Instance;

            sudokuFieldProvider.SetInitialList(InitializeSquares(ReadFile()));
            SudokuSolver c = new SudokuSolver(sudokuFieldProvider);

            List <Thread> allThreads = new List <Thread>();

            for (int x = 0; x < Environment.ProcessorCount; x++)
            {
                Thread thread = new Thread(new ThreadStart(c.GetSolutions));
                thread.Start();
                allThreads.Add(thread);
            }

            foreach (Thread thread in allThreads)
            {
                thread.Join();
            }

            WriteResult(sudokuFieldProvider.GetResultList());

            Console.ReadLine();
        }
示例#5
0
        //indexShowFirst = The index where most cells were set
        public void Process(out ArrayList resultStrings, out ArrayList sudokuBoardStrings, out ArrayList listBoxEntries, out int indexShowFirst)
        {
            Random    random = new Random((int)(DateTime.Now.Ticks % (long)int.MaxValue));
            string    ResultStr, iterationDebugDirectory, debugDirectory;
            int       numberOfTries = 0, maxCellsSetInATry = -1, totalNumberOfCellsSet, numberOfCellsSetInTry;
            ArrayList result = new ArrayList();

            resultStrings      = new ArrayList();
            sudokuBoardStrings = new ArrayList();
            listBoxEntries     = new ArrayList();
            indexShowFirst     = -1;

            debugDirectory = _debugDirectory + "\\Solve_Sudoku_" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.fff");

            Directory.CreateDirectory(debugDirectory);

            SudokuSolver sudokuSolver = new SudokuSolver(random, _sudokuBoard, _isDebug);

            while ((numberOfTries < _maxNumberOfTries) && !_sudokuBoard.SudokuIsSolved)
            {
                numberOfTries++;
                iterationDebugDirectory = debugDirectory + "\\Try" + numberOfTries.ToString();
                Directory.CreateDirectory(iterationDebugDirectory);
                result = sudokuSolver.Process(iterationDebugDirectory, out ResultStr);
                resultStrings.Add(ResultStr);
                sudokuBoardStrings.Add(_sudokuBoard.SudokuBoardString);
                totalNumberOfCellsSet = _sudokuBoard.NumberOfCellsSet;
                numberOfCellsSetInTry = result.Count;
                listBoxEntries.Add(string.Format("Try{0} ({1}, {2}, {3})", numberOfTries, totalNumberOfCellsSet, _numberOfCellsSetInOriginalData, numberOfCellsSetInTry));

                if ((_originalData.Count + result.Count) != totalNumberOfCellsSet)
                {
                    throw new Exception("if ((_originalData.Count + result.Count) != totalNumberOfCellsSet)");
                }

                if (numberOfTries == 1)
                {
                    maxCellsSetInATry = totalNumberOfCellsSet;
                    indexShowFirst    = 0;
                }
                else if ((numberOfTries > 1) && (totalNumberOfCellsSet > maxCellsSetInATry))
                {
                    maxCellsSetInATry = totalNumberOfCellsSet;
                    indexShowFirst    = numberOfTries - 1;
                }

                if (_sudokuBoard.SudokuIsSolved)
                {
                    if ((_originalData.Count + result.Count) != 81)
                    {
                        throw new Exception("((_originalData.Count + result.Count) != 81) in method SolveSudoku.Process");
                    }
                }
                else if (numberOfTries < _maxNumberOfTries)
                {
                    _sudokuBoard.Reset(_originalData);
                }
            }
        }
示例#6
0
        private void SolveSudoku(object sender, RoutedEventArgs e)
        {
            var sudokuSolver    = new SudokuDifficulty();
            var sudokuValidator = new SudokuSolver();
            var sudokuToSolve   = new SudokuCell[9, 9];

            var counter = 0;

            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    var textBox = this.FindName("TextBox" + counter) as TextBox;
                    sudokuToSolve[row, col] = new SudokuCell(row, col);
                    if (textBox.Text != string.Empty)
                    {
                        sudokuToSolve[row, col].Value = int.Parse(textBox.Text);
                    }
                    counter++;
                }
            }

            if (lastSudokuDifficulty == 0)
            {
                MessageBox.Show("You must first generate a sudoku!");
                return;
            }

            if (!sudokuValidator.CheckIfSudokuIsValid(sudokuToSolve))
            {
                MessageBox.Show("This sudoku is not valid! Please check for errors!", "Warning");
                return;
            }

            try
            {
                sudokuToSolve = sudokuSolver.SolveSudoku(sudokuToSolve);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("This sudoku is not valid! Please check for errors!", "Warning");
                return;
            }

            counter = 0;

            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    var textBox = this.FindName("TextBox" + counter) as TextBox;
                    textBox.Text      = string.Empty;
                    textBox.Text      = sudokuToSolve[row, col].Value.ToString();
                    textBox.IsEnabled = false;
                    counter++;
                }
            }
            stopWatch.Stop();
        }
示例#7
0
        private void SolveSudoku()
        {
            grid.ClearUserCells();

            SudokuSolver solver = new SudokuSolver(grid);

            solver.Solve();
            RefreshCellValues();
        }
示例#8
0
        static void Main(string[] args)
        {
            var validator    = new GridValidator();
            var solver       = new SudokuSolver(validator);
            var generator    = new SudokuGenerator(validator, solver);
            var policy       = new HardPuzzlePolicy();
            var sudukoPuzzle = generator.GeneratePuzzle(policy);

            sudukoPuzzle.Print();
            Console.WriteLine($"Num blanks in puzzle: {validator.GetNumBlanks(sudukoPuzzle.puzzleGrid)}");
        }
示例#9
0
        private void SolveSudoku()
        {
            //Clear user input
            grid.ClearUserCells();

            //Init solver and do magic
            SudokuSolver solver = new SudokuSolver(grid);

            solver.Solve();
            RefreshCellValues();
        }
示例#10
0
        public void OnCover(ExactCover ec, SudokuCandidate sc)
        {
            int cage = sc.c;
            int num  = sc.n + 1;

            System.Diagnostics.Debug.Assert(info.sizes[cage] > 0);
            SudokuSolver ss = (SudokuSolver)ec;

            info.remaining_totals[cage] -= num;
            info.remaining_sizes[cage]--;
            removed = CheckRemains(ss, info, cage, num);
        }
示例#11
0
        static void Main()
        {
            var SudokuSolver = new SudokuSolver();
            var board        = GetBoard(Boards.HardMetro);

            PrettyPrinter.PrettyPrint(board);
            var solvedBoard = SudokuSolver.Solve(board, _debug);

            PrettyPrinter.PrettyPrint(solvedBoard);
            Console.WriteLine(IsSolved(solvedBoard));
            Console.ReadKey();
        }
示例#12
0
        static void Main(string[] args)
        {
            FillBoard();

            SudokuSolver solver = new SudokuSolver(board);

            Console.WriteLine(board);
            solver.Solve();
            Console.WriteLine(board);

            Console.ReadKey();
        }
        /// <summary>
        /// Determines whether a specified <c><paramref name="sudoku"/></c> can be solved.
        /// </summary>
        /// <param name="sudoku">The <see cref="T:Sudoku.Sudoku"/> puzzle to check.</param>
        /// <param name="multipleSolutions"><c>true</c> if <c><paramref name="sudoku"/></c> has multiple possible solutions; otherwise, <c>false</c>.</param>
        /// <returns><c>true</c> if <c><paramref name="sudoku"/></c> has one or more possible solution; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException"><c><paramref name="sudoku"/></c> is <c>null</c>.</exception>
        public static bool CheckSolvable(SudokuPuzzle sudoku, out bool multipleSolutions)
        {
            if (sudoku is null)
            {
                throw new ArgumentNullException(nameof(sudoku));
            }

            int count = 0;

            SudokuSolver.RecursiveSolve((SudokuPuzzle)sudoku.Clone(), 0, 0, ref count, true);
            multipleSolutions = count > 1;
            return(count != 0);
        }
        /// <summary>
        /// Fills an existing <see cref="SudokuPuzzle"/> with numbers.
        /// </summary>
        /// <param name="sudoku">The puzzle to fill with numbers.</param>
        /// <exception cref="ArgumentNullException"><c><paramref name="sudoku"/></c> is <c>null</c>.</exception>
        public static void AddNumbers(SudokuPuzzle sudoku)
        {
            if (sudoku is null)
            {
                throw new ArgumentNullException(nameof(sudoku));
            }

            sudoku.DisablePossible = true;
            SudokuSolver.RecursiveSolve(sudoku);
            sudoku.DisablePossible = false;
            sudoku.ResetPossible();
            sudoku.ClearReadOnlyProperties();
            sudoku.SetSolutions();
        }
        /// <summary>
        /// Solve the specified <see cref="T:Sudoku.Sudoku"/> puzzle using recursion, otherwise known as "brute-force".
        /// </summary>
        /// <param name="sudoku">The <see cref="T:Sudoku.Sudoku"/> puzzle to solve.</param>
        /// <exception cref="ArgumentNullException"><c><paramref name="sudoku"/></c> is <c>null</c>.</exception>
        public static void RecursiveSolve(SudokuPuzzle sudoku)
        {
            if (sudoku is null)
            {
                throw new ArgumentNullException(nameof(sudoku));
            }

            int count = 0;

            sudoku.DisablePossible = true;
            SudokuSolver.RecursiveSolve(sudoku, 0, 0, ref count);
            sudoku.DisablePossible = false;
            sudoku.ResetPossible();
        }
示例#16
0
        private void CheckIfDigit(object sender, TextCompositionEventArgs e)
        {
            try
            {
                if (!char.IsDigit(e.Text, e.Text.Length - 1))
                {
                    e.Handled = true;
                    return;
                }
                else
                {
                    (sender as TextBox).Text = e.Text;
                }


                var sudokuToSolve   = new SudokuCell[9, 9];
                var sudokuValidator = new SudokuSolver();

                var counter      = 0;
                var numbersCount = 0;
                for (int row = 0; row < 9; row++)
                {
                    for (int col = 0; col < 9; col++)
                    {
                        var textBox = this.FindName("TextBox" + counter) as TextBox;
                        sudokuToSolve[row, col] = new SudokuCell(row, col);
                        if (textBox.Text != string.Empty)
                        {
                            sudokuToSolve[row, col].Value = int.Parse(textBox.Text);
                            numbersCount++;
                        }
                        counter++;
                    }
                }

                if (numbersCount == 81)
                {
                    if (!sudokuValidator.CheckIfSudokuIsValid(sudokuToSolve))
                    {
                        MessageBox.Show("This sudoku is not valid! Please check for errors!", "Warning");
                        return;
                    }
                    MessageBox.Show("Congratulations! You solved this sudoku for: " + GetTime() + "!");
                }
            }
            catch (Exception)
            {
            }
        }
示例#17
0
        public static void Main(string[] args)
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            var sudoku     = new Sudoku("./input.txt");
            var visualiser = new SudokuVisualiser(sudoku);
            var solver     = new SudokuSolver(sudoku, visualiser);

            solver.Solve();

            stopWatch.Stop();
            Console.WriteLine($"Finished in {stopWatch.Elapsed}");
        }
示例#18
0
 public void ClearGrid(GridOptions options)
 {
     this.cageInfo    = null;
     this.gridOptions = options;
     values           = new int[Cells, Cells];
     flags            = new CellFlags[Cells, Cells];
     for (int x = 0; x < Cells; ++x)
     {
         for (int y = 0; y < Cells; ++y)
         {
             values[x, y] = -1;
             flags[x, y]  = CellFlags.Free;
         }
     }
     solver = new SudokuSolver(this);
 }
示例#19
0
        private void button_Solve_Click(object sender, EventArgs e)
        {
            var timer = Stopwatch.StartNew();

            SudokuSolver sudokuSolver = new SudokuSolver(Sudoku);

            sudokuSolver.SolveSudoku();
            var log = sudokuSolver.Log;

            Heatmap          = log.Heatmap;
            textBox_Log.Text = log.LogText;

            Text = timer.ElapsedMilliseconds + " ms";

            pictureBox1.Refresh();
        }
        private static bool RecursiveSolveNextNumber(SudokuPuzzle sudoku, int row, int column, ref int count, bool findMultiple = false)
        {
            int nextColumn = column + 1, nextRow = row;

            if (nextColumn == sudoku.Size)
            {
                nextRow++;
                nextColumn = 0;
            }

            if (nextRow == sudoku.Size)
            {
                count++;
                return(true);
            }

            return(SudokuSolver.RecursiveSolve(sudoku, nextRow, nextColumn, ref count, findMultiple));
        }
示例#21
0
        private void textBox_SudokuStr_Validated(object sender, EventArgs e)
        {
            var str = textBox_SudokuStr.Text.Trim();

            // Check how many chars
            if (str.Length != 9 * 9)
            {
                return;
            }

            // check each char
            foreach (var c in str)
            {
                if ((c != '.')
                    &&
                    (c < '0' || c > '9'))
                {
                    return;
                }
            }

            // Clear model
            Sudoku.Initialize();
            PresetIndexes.Clear();

            for (byte i = 0; i < str.Length; i++)
            {
                char c       = str[i];
                byte byteVal = c == '.' ? NDEF_VALUE : (byte)(c - '0');

                Sudoku[i] = byteVal;

                if (byteVal != NDEF_VALUE)
                {
                    PresetIndexes.Add(i);
                }
            }

            // Init solver
            Solver = new SudokuSolver(Sudoku);

            // Repaint
            pictureBox1.Refresh();
        }
        /// <summary>
        /// Removes numbers from an existing <see cref="SudokuPuzzle"/> according to its difficulty.
        /// </summary>
        /// <param name="sudoku">The <see cref="SudokuPuzzle"/> to remove numbers from.</param>
        /// <exception cref="ArgumentNullException"><c><paramref name="sudoku"/></c> is <c>null</c>.</exception>
        public static void RemoveNumbers(SudokuPuzzle sudoku)
        {
            if (sudoku is null)
            {
                throw new ArgumentNullException(nameof(sudoku));
            }

            sudoku.ClearReadOnlyProperties();
            int attempts = 45;

            switch (sudoku.Difficulty)
            {
            case SudokuDifficulty.Medium:
                attempts = 60;
                break;

            case SudokuDifficulty.Hard:
                attempts = 75;
                break;
            }

            do
            {
                int row, column;

                do
                {
                    row    = SudokuGenerator.Random.Next(sudoku.Size);
                    column = SudokuGenerator.Random.Next(sudoku.Size);
                } while (sudoku[row, column] == 0);

                int value = sudoku[row, column];
                sudoku[row, column] = 0;
                bool solvable = SudokuSolver.CheckSolvable(sudoku, out bool multipleSolutions);

                if (!solvable || multipleSolutions)
                {
                    sudoku[row, column] = value;
                }
            } while (attempts-- > 0);

            sudoku.SetReadOnlyProperties();
        }
示例#23
0
 public void ResetSolver()
 {
     if (cageInfo != null)
     {
         cageInfo.Reset();
     }
     for (int x = 0; x < Cells; x++)
     {
         for (int y = 0; y < Cells; y++)
         {
             if (FlagAt(x, y) == CellFlags.Solved)
             {
                 flags[x, y]  = CellFlags.Free;
                 values[x, y] = -1;
             }
         }
     }
     solver = new SudokuSolver(this);
     Updated();
 }
示例#24
0
        private List <byte> EliminationSearch(IEnumerable <byte> rowColCellSearchSolutions)
        {
            var eliminationSearchSolutions = new List <byte>();

            foreach (var recentlyFoundIndex in rowColCellSearchSolutions)
            {
                var eliminatedElements = new List <byte>();

                // store digit for later
                var digit = Sudoku[recentlyFoundIndex];

                // Remove all line, col and cell entries (cannot go there again)
                foreach (var removerIndex in
                         SudokuSolver.GetRowIterator(recentlyFoundIndex)
                         .Union(SudokuSolver.GetColIterator(recentlyFoundIndex))
                         .Union(SudokuSolver.GetCellIterator(recentlyFoundIndex))
                         )
                {
                    var possibleSolutions = PossibilitySpace[removerIndex];

                    // Check if already set
                    if (possibleSolutions is null)
                    {
                        continue;
                    }

                    // Remove possibility
                    possibleSolutions.Remove(digit);

                    // check if only solution
                    if (possibleSolutions.Count == 1)
                    {
                        ProcessNewMatch(possibleSolutions.First(), (byte)removerIndex, ref eliminatedElements);
                    }
                }

                eliminationSearchSolutions.AddRange(eliminatedElements);
            }

            return(eliminationSearchSolutions);
        }
        private bool CheckMoveMade(int row, int column, int number, SudokuPattern pattern)
        {
            if (this.Moves.Count == 0)
            {
                return(false);
            }

            int count = 0;

            foreach (SudokuMove move in this)
            {
                count++;
                int nextCount = 0;

                foreach (SudokuMove nextMove in this)
                {
                    nextCount++;
                    if (Object.ReferenceEquals(move, nextMove))
                    {
                        continue;
                    }

                    if (SudokuSolver.Compare(move.Rows, nextMove.Rows) && SudokuSolver.Compare(move.Columns, nextMove.Columns) && SudokuSolver.Compare(move.Numbers, nextMove.Numbers) && move.Pattern == nextMove.Pattern)
                    {
                        return(true);
                    }
                }
            }

            foreach (SudokuMove move in this)
            {
                if (move.Pattern == pattern && move.Rows.Contains(row) && move.Columns.Contains(column) && move.Numbers.Contains(number))
                {
                    return(true);
                }
            }

            return(false);
        }
示例#26
0
		public static void Main (string[] args)
		{
			int[,] input = new int[9,9] {
				{7,2,0,0,3,9,0,0,6},
				{0,0,0,0,5,0,3,0,1},
				{0,0,0,0,0,7,0,0,5},
				{0,0,0,0,0,0,1,0,0},
				{9,0,6,0,0,0,0,0,2},
				{0,3,0,0,0,0,5,0,0},
				{3,7,0,0,0,4,8,0,0},
				{6,0,8,9,7,0,0,3,0},
				{5,0,0,0,0,0,0,0,0}
			};

//			int[,] input = new int[9,9] {
//				{7,2,5,1,3,9,4,8,6},
//				{4,6,9,2,5,8,3,7,1},
//				{1,8,3,4,6,7,9,2,5},
//				{8,4,7,5,9,2,1,6,3},
//				{9,5,6,3,8,1,7,4,2},
//				{2,3,1,7,4,6,5,9,8},
//				{3,7,2,6,1,4,8,5,9},
//				{6,1,8,9,7,5,2,3,4},
//				{5,9,4,8,2,3,6,1,7}
//			};


//			int[,] input = new int[4, 4] {
//				{ 0, 2, 0, 1 } ,
//				{ 1, 0, 0, 4 } ,
//				{ 0, 4, 1, 3 } ,
//				{ 3, 0, 4, 0 } 
//			};

			SudokuSolver ss = new SudokuSolver (input);
			ss.Print ();

			Console.WriteLine ("");
		}
        private static bool RecursiveSolve(SudokuPuzzle sudoku, int row, int column, ref int count, bool findMultiple = false)
        {
            if (sudoku[row, column] != 0)
            {
                return(SudokuSolver.RecursiveSolveNextNumber(sudoku, row, column, ref count, findMultiple));
            }

            List <int> possible = new List <int>();

            for (int i = 1; i <= sudoku.Size; i++)
            {
                if (!(sudoku.RowContains(row, i) || sudoku.ColumnContains(column, i) || sudoku.BlockContains(row, column, i)))
                {
                    possible.Add(i);
                }
            }

            SudokuSolver.ShuffleNumbers(possible);

            while (possible.Count > 0)
            {
                sudoku[row, column] = possible[0];
                bool solvable = SudokuSolver.RecursiveSolveNextNumber(sudoku, row, column, ref count, findMultiple);

                if (solvable)
                {
                    if (!findMultiple || count > 1)
                    {
                        return(true);
                    }
                }

                possible.RemoveAt(0);
            }

            sudoku[row, column] = 0;
            return(false);
        }
示例#28
0
        public static void Main(string[] args)
        {
            int[,] input = new int[9,9] {
                {7,2,0,0,3,9,0,0,6},
                {0,0,0,0,5,0,3,0,1},
                {0,0,0,0,0,7,0,0,5},
                {0,0,0,0,0,0,1,0,0},
                {9,0,6,0,0,0,0,0,2},
                {0,3,0,0,0,0,5,0,0},
                {3,7,0,0,0,4,8,0,0},
                {6,0,8,9,7,0,0,3,0},
                {5,0,0,0,0,0,0,0,0}
            };

            //			int[,] input = new int[9,9] {
            //				{7,2,5,1,3,9,4,8,6},
            //				{4,6,9,2,5,8,3,7,1},
            //				{1,8,3,4,6,7,9,2,5},
            //				{8,4,7,5,9,2,1,6,3},
            //				{9,5,6,3,8,1,7,4,2},
            //				{2,3,1,7,4,6,5,9,8},
            //				{3,7,2,6,1,4,8,5,9},
            //				{6,1,8,9,7,5,2,3,4},
            //				{5,9,4,8,2,3,6,1,7}
            //			};

            //			int[,] input = new int[4, 4] {
            //				{ 0, 2, 0, 1 } ,
            //				{ 1, 0, 0, 4 } ,
            //				{ 0, 4, 1, 3 } ,
            //				{ 3, 0, 4, 0 }
            //			};

            SudokuSolver ss = new SudokuSolver (input);
            ss.Print ();

            Console.WriteLine ("");
        }
示例#29
0
        public static SudokuCandidate[] CheckRemains(SudokuSolver ss, SudokuGrid.CageInfo info, int cage, int ex)
        {
            int s = info.remaining_sizes[cage];

            if (s == 1)
            {
                // One empty cell remains in the cage, so make the total
                int total = info.remaining_totals[cage];
                return(Filter(ss, cage, (int n) => (n == total)));
            }

            /*
             * else if(s > 1)
             * {
             * // 's' numbers left to choose from
             * int total = info.remaining_totals[cage];
             * int m0 = total - 45 + (11 - s) * (10 - s) / 2;
             * int m1 = total - s * (s - 1) / 2;
             * Filter(ss, cage, (int n) => n == ex || (n >= m0 && n <= m1));
             * }
             * */
            return(null);
        }
示例#30
0
        static void Main(string[] args)
        {
            var boardMaster = new SudokuSolver();

            //  var board = boardMaster.SetBoard();
            var board = boardMaster.ReadBoardFromFile();

            var result = boardMaster.Solve(board);

            foreach (var salution in result)
            {
                boardMaster.Print(salution);
                Console.WriteLine(new string('-', 17));
            }

            if (result.Count() > 1)
            {
                Console.WriteLine("Salutions count: " + result.Count());
            }
            else if (result.Count() == 0)
            {
                Console.WriteLine("No solution possible!");
            }
        }
示例#31
0
        public static void Main(string[] args)
        {
            bool verbose = false;

            if (args.Length > 0)
            {
                verbose = args[0].Equals("v");
            }
            int i = 0;

            int[][] matrix = new int[9][];
            while (i < 9)
            {
                string   s    = Console.ReadLine();
                string[] line = s.Split(' ');
                if (line.Length == 9)
                {
                    int[] intArr = new int[9];
                    for (int j = 0; j < 9; j++)
                    {
                        int x = int.Parse(line[j]);
                        intArr[j] = x;
                    }
                    //sud.AddRow(intArr);
                    matrix[i] = intArr;
                    i++;
                }
                else
                {
                    //invalid, please retype
                    Console.WriteLine("invalid line, please retype");
                    continue;
                }
            }
            Console.WriteLine();
            PrintMatrix(matrix);

            DateTime startTime = DateTime.Now;

            Console.WriteLine("Started: {0}", startTime);

            //SudokuSolver_old solver = new SudokuSolver_old(sud);
            //solver.Iterate(false);
            SudokuSolver solver = new SudokuSolver(matrix, verbose);

            solver.Solve();


            DateTime stopTime = DateTime.Now;

            Console.WriteLine("Stopped: {0}", stopTime);
            Console.WriteLine("solution generated: {0}", solver.possibleSolutions.Count);
            Console.WriteLine("backtracks: {0}", solver.deadendCount);

            foreach (int[][] solution in solver.possibleSolutions)
            {
                PrintMatrix(solution);
            }
            Console.WriteLine();


            TimeSpan elapsedTime = stopTime - startTime;

            Console.WriteLine("Elapsed: {0}", elapsedTime);
            Console.WriteLine("in hours       :" + elapsedTime.TotalHours);
            Console.WriteLine("in minutes     :" + elapsedTime.TotalMinutes);
            Console.WriteLine("in seconds     :" + elapsedTime.TotalSeconds);
            Console.WriteLine("in milliseconds:" + elapsedTime.TotalMilliseconds);
        }
示例#32
0
 private void SolverToolStripMenuItem_Click(object sender, EventArgs e)
 {
     DialogResult EstaSeguro = MessageBox.Show("Esta seguro que desea resolver el sudoku actual? No podra terminarlo una vez haya confirmado."
         , "Resolver Sudoku?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
     if (EstaSeguro == DialogResult.Yes)
     {
         Sudoku ToBeSolved;
         List<int> Fields = new List<int>();
         for (int i = 0; i < 9; i++)
         {
             for (int j = 0; j < 9; j++)
             {
                 if (Texts[i][j].Text == "")
                     Fields.Add(0);
                 else
                     Fields.Add(int.Parse(Texts[i][j].Text));
             }
         }
         ToBeSolved = new Sudoku(Fields);
         SudokuSolver Solver = new SudokuSolver();
         Sudoku Result = Solver.Solve(ToBeSolved, false, 4);
         Resolviendo = true;
         Display(Result);
         Resolviendo = false;
         SolverToolStripMenuItem.Enabled = false;
     }
     else
     {
         MessageBox.Show("Adelante no te desesperes, todavia se puede!", "Tu puedes", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
示例#33
0
        private void SolveSudoku()
        {
            //Clear user input
            grid.ClearUserCells();

            //Init solver and do magic
            SudokuSolver solver = new SudokuSolver(grid);
            solver.Solve();
            RefreshCellValues();
        }
        static void Main(string[] args)
        {
            int[,] professorSudoku = new int[9, 9] {
                { 3, 7, 0, 5, 0, 0, 0, 0, 6 },
                { 0, 0, 0, 3, 6, 0, 0, 1, 2 },
                { 0, 0, 0, 0, 9, 1, 7, 5, 0 },
                { 0, 0, 0, 1, 5, 4, 0, 7, 0 },
                { 0, 0, 3, 0, 7, 0, 6, 0, 0 },
                { 0, 5, 0, 6, 3, 8, 0, 0, 0 },
                { 0, 6, 4, 9, 8, 0, 0, 0, 0 },
                { 5, 9, 0, 0, 2, 6, 0, 0, 0 },
                { 2, 0, 0, 0, 0, 5, 0, 6, 4 }
            };
            // World most difficult sudoku
            // http://aisudoku.com/index_en.html
            // http://www.telegraph.co.uk/news/science/science-news/9359579/Worlds-hardest-sudoku-can-you-crack-it.html
            // http://www.mirror.co.uk/news/weird-news/worlds-hardest-sudoku-puzzle-ever-942299


            int[,] worldSudoku = new int[9, 9] {
                { 8, 0, 0, 0, 0, 0, 0, 0, 0 },
                { 0, 0, 3, 6, 0, 0, 0, 0, 0 },
                { 0, 7, 0, 0, 9, 0, 2, 0, 0 },
                { 0, 5, 0, 0, 0, 7, 0, 0, 0 },
                { 0, 0, 0, 0, 4, 5, 7, 0, 0 },
                { 0, 0, 0, 1, 0, 0, 0, 3, 0 },
                { 0, 0, 1, 0, 0, 0, 0, 6, 8 },
                { 0, 0, 8, 5, 0, 0, 0, 1, 0 },
                { 0, 9, 0, 0, 0, 0, 4, 0, 0 }
            };



            SudokuSolver ss = new SudokuSolver(professorSudoku);


            Console.WriteLine("--------------- ProfessorSudoku ---------------\n{0}", ss);
            if (ss.Backtracking())
            {
                Console.WriteLine("ProfessorSudoku - Simple Backtracking SOLUTION in {0} steps :\n{1}", SudokuSolver.NCALL, ss);
            }
            else
            {
                Console.WriteLine("ProfessorSudoku - Simple Backtracking NO SOLUTION");
            }

            ss.SetSudoku(professorSudoku);
            ss.PreliminaryCheck();
            if (ss.BacktrackingConstr())
            {
                Console.WriteLine("Sudoku - Constraint Propagation SOLUTION in {0} steps :\n{1}", SudokuSolver.NCALL, ss);
            }
            else
            {
                Console.WriteLine("Sudoku - Constraint Propagation NO SOLUTION");
            }


            ss.SetSudoku(worldSudoku);
            Console.WriteLine("--------------- World most difficult Sudoku ---------------\n{0}", ss);
            if (ss.Backtracking())
            {
                Console.WriteLine("World most difficult - Simple Backtracking SOLUTION in {0} steps :\n{1}", SudokuSolver.NCALL, ss);
            }
            else
            {
                Console.WriteLine("World most difficult  - Simple Backtracking NO SOLUTION");
            }

            ss.SetSudoku(worldSudoku);
            ss.PreliminaryCheck();
            if (ss.BacktrackingConstr())
            {
                Console.WriteLine("Sudoku - Constraint Propagation SOLUTION in {0} steps :\n{1}", SudokuSolver.NCALL, ss);
            }
            else
            {
                Console.WriteLine("Sudoku - Constraint Propagation NO SOLUTION");
            }



            /*
             * //TIC
             * var watch = Stopwatch.StartNew();
             *
             * ss.SetSudoku(sudoku);
             *
             * if (ss.RelaxationLabelingALC())
             * Console.WriteLine("Sudoku - Relaxation Labeling SOLUTION in {0} steps :\n{1}", SudokuSolver.NCALL, ss);
             * else
             * Console.WriteLine("Sudoku - Relaxation Labeling NO SOLUTION");
             *
             * //TOC
             * watch.Stop();
             * var elapsedMs = watch.ElapsedMilliseconds;
             * Console.WriteLine("[DEBUG]> Elapsed time: {0}", elapsedMs);
             */

            Console.ReadLine();
        }
示例#35
0
        public List <SmallSquare> GetAllPossibleSquares(List <SmallSquare> listOfSquares, int xPosition, int yPosition, HashSet <string> invalidFields, int smallSquareNumber)
        {
            int elementCounter = 0;

            if (listOfSquares.Count == 0)
            {
                listOfSquares.Add(this);
            }

            if (yPosition == 3)
            {
                System.Diagnostics.Debug.WriteLine("GetAllPossibleSquares return");

                Dictionary <string, SmallSquare> newList = new Dictionary <string, SmallSquare>();

                foreach (SmallSquare sq in listOfSquares)
                {
                    bool isOK = true;
                    if (smallSquareNumber < 6)
                    {
                        for (int y = 0; y < 3; y++)
                        {
                            for (int x = 0; x < 3; x++)
                            {
                                if (!sq.Fields[y, x].IsFixed)
                                {
                                    if (invalidFields.Contains(SudokuSolver.GetBlockListEntry(smallSquareNumber, sq.Fields[y, x].FieldValue, x, y)))
                                    {
                                        isOK = false;
                                        break;
                                    }
                                }

                                if (!isOK)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (isOK && sq.IsComplete())
                    {
                        if (!newList.ContainsKey(sq.GetKey()))
                        {
                            newList.Add(sq.GetKey(), sq);
                        }
                    }
                }

                if (!newList.Any())
                {
                    System.Diagnostics.Debug.WriteLine("no results");
                }

                return(newList.Select(val => val.Value).ToList());
            }

            Dictionary <string, SmallSquare> newSquares = new Dictionary <string, SmallSquare>();

            foreach (SmallSquare existingSquare in listOfSquares)
            {
                elementCounter = 0;

                for (int x = 0; x < 9; x++)
                {
                    SmallSquare   newSquare        = Program.DeepClone(existingSquare);
                    HashSet <int> availableNumbers = newSquare.GetNumbersStillAvailable();

                    if (newSquare.Fields[yPosition, xPosition].IsFixed == false)
                    {
                        newSquare.Fields[yPosition, xPosition].FieldValue = availableNumbers.ElementAt(elementCounter);
                        elementCounter++;
                    }

                    if (!newSquares.ContainsKey(newSquare.GetKey()))
                    {
                        newSquares.Add(newSquare.GetKey(), newSquare);
                    }


                    if (availableNumbers.Count() == elementCounter)
                    {
                        break;
                    }
                }
            }

            if (xPosition == 2)
            {
                xPosition = 0;
                yPosition++;
            }
            else
            {
                xPosition++;
            }

            return(GetAllPossibleSquares(newSquares.Select(val => val.Value).ToList(), xPosition, yPosition, invalidFields, smallSquareNumber));
        }
示例#36
0
 public Sudoku Resolver(Sudoku ToBeSolved)
 {
     SudokuSolver Solver = new SudokuSolver();
     Sudoku Result = Solver.Solve(ToBeSolved, false, 4);
     return Result;
 }
示例#37
0
 public Boolean sePuedeResolver(Sudoku ToBeSolved)
 {
     SudokuSolver Solver = new SudokuSolver();
     Sudoku Result = Solver.Solve(ToBeSolved, false, 4);
     if (Result != null)
         return true;
     else
         return false;
 }
示例#38
0
        private bool DeleteField(Sudoku temp, ref int difficulty)
        {
            int i = Rnd.Next(0, 9); ;
            int j = Rnd.Next(0, 9); ;

            // select random not yet deleted field
            while (!temp.Fields[i][j].Filled)
            {
                i = Rnd.Next(0, 9);
                j = Rnd.Next(0, 9);
            }

            temp.Fields[i][j].Value = 0;
            temp.Fields[i][j].Filled = false;
            SudokuSolver Test = new SudokuSolver();
            int Difficulty = difficulty;
            // check the desired characteristics
            Sudoku Temp = Test.Solve(temp.Copy(), true, Difficulty);
            if (Temp == null)
                return false;
            temp.Difficulty = Temp.Difficulty;
            if (Temp.NrSolutions > 1 || Temp.Difficulty > Difficulty)
                return false;
            else
                return true;
        }