private void CreatePuzzleGrid(SudokuPuzzle puzzle, int maxBlanks)
        {
            var  puzzleGrid = CopyGrid(puzzle.puzzleGrid);
            int  numBlanks  = maxBlanks;
            bool found      = false;

            //
            // Start with number of blanks as specified in policy
            // If multiple solutions are found, decrease the number of blank
            // cells until a single solution is found
            while (!found && numBlanks > 0)
            {
                int numRetries = 10;
                int retries    = 0;
                while (retries < numRetries && !found)
                {
                    var rng        = new Random(Guid.NewGuid().GetHashCode());
                    var backupGrid = CopyGrid(puzzleGrid);

                    int numRemainingBlanks = numBlanks;

                    while (numRemainingBlanks > 0)
                    {
                        int row = rng.Next(9);
                        int col = rng.Next(9);
                        while (puzzleGrid[row, col] == 0)
                        {
                            row = rng.Next(9);
                            col = rng.Next(9);
                        }
                        puzzleGrid[row, col] = 0;
                        numRemainingBlanks--;
                    }

                    var copy = CopyGrid(puzzleGrid);

                    puzzle.NumSolutions = _solver.SolveGrid(copy);
                    if (puzzle.NumSolutions > 1)
                    {
                        Console.WriteLine($"Too many solutions: {puzzle.NumSolutions}");
                    }
                    else if (puzzle.NumSolutions == 0)
                    {
                        Console.WriteLine("No solution found");
                    }

                    if (puzzle.NumSolutions != 1)
                    {
                        puzzleGrid = backupGrid;
                    }
                    else
                    {
                        found = true;
                    }
                    retries++;
                }
                numBlanks--;
            }
            puzzle.puzzleGrid = CopyGrid(puzzleGrid);
        }
示例#2
0
        public SudokuGrid()
        {
            InitializeComponent();

            this._puzzle = new SudokuPuzzle() { Rank = 3 };
            this._zones = new SudokuZone[this._puzzle.Rank, this._puzzle.Rank];

            // Load the UI
            StackPanel gridStackPanel = new StackPanel() { Orientation = Orientation.Vertical };

            for (int i = 0; i < this._puzzle.Rank; i++)
            {
                StackPanel rowStackPanel = new StackPanel() { Orientation = Orientation.Horizontal };

                for (int j = 0; j < this._puzzle.Rank; j++)
                {
                    SudokuZone zone = new SudokuZone();
                    this._zones[i, j] = zone;
                    rowStackPanel.Children.Add(zone);
                }

                gridStackPanel.Children.Add(rowStackPanel);
            }

            this.SudokuZoneContainer.Child = gridStackPanel;
        }
        /// <summary>
        /// Generates a new <see cref="SudokuPuzzle"/> by filling it with numbers and then removing numbers according to <c><paramref name="difficulty"/></c>.
        /// </summary>
        /// <param name="size">The number of elements that the new <see cref="SudokuPuzzle"/> can store in each row, column and block.</param>
        /// <param name="difficulty">The difficulty associated with the <see cref="SudokuPuzzle"/>.</param>
        /// <returns>A new <see cref="SudokuPuzzle"/>.</returns>
        /// <exception cref="ArgumentException"><c><paramref name="size"/></c> is not a positive, square integer - or - <c><paramref name="difficulty"/></c> is equal to <see cref="SudokuDifficulty.None"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><c><paramref name="size"/></c> is less than or equal to 0 or greater than <see cref="SudokuPuzzle.MaximumSupportedSize"/>.</exception>
        public static SudokuPuzzle Generate(int size, SudokuDifficulty difficulty)
        {
            SudokuPuzzle sudoku = SudokuGenerator.AddNumbers(size, difficulty);

            SudokuGenerator.RemoveNumbers(sudoku);
            return(sudoku);
        }
示例#4
0
        public void Initialize(SudokuPuzzle puzzle)
        {
            if (puzzle == null)
                return;

            _puzzle = (SudokuPuzzle)puzzle.Clone();

            UpdateTextBoxes();
        }
        public SudokuPuzzle GeneratePuzzle(IPuzzlePolicy policy)
        {
            var puzzle = new SudokuPuzzle();

            FillGrid(puzzle.FullGrid);
            puzzle.puzzleGrid = CopyGrid(puzzle.FullGrid);
            CreatePuzzleGrid(puzzle, policy.MaxBlanks);
            return(puzzle);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            if (_values == null)
            {
                Create_Cells();
                Create_Boxes();
            }

            puzzle = new SudokuPuzzle(9);
        }
        /// <summary>
        /// Creates a new <see cref="SudokuPuzzle"/> and fills it with numbers.
        /// </summary>
        /// <param name="size">The number of elements that the new <see cref="SudokuPuzzle"/> can store in each row, column and block.</param>
        /// <param name="difficulty">The difficulty associated with the <see cref="SudokuPuzzle"/>.</param>
        /// <returns>A new <see cref="SudokuPuzzle"/> filled with numbers.</returns>
        /// <exception cref="ArgumentException"><c><paramref name="size"/></c> is not a positive, square integer - or - <c><paramref name="difficulty"/></c> is equal to <see cref="SudokuDifficulty.None"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><c><paramref name="size"/></c> is less than or equal to 0 or greater than <see cref="SudokuPuzzle.MaximumSupportedSize"/>.</exception>
        public static SudokuPuzzle AddNumbers(int size, SudokuDifficulty difficulty)
        {
            if (difficulty == SudokuDifficulty.None)
            {
                throw new ArgumentException(nameof(difficulty));
            }

            SudokuPuzzle sudoku = new SudokuPuzzle(size, difficulty);

            SudokuGenerator.AddNumbers(sudoku);
            return(sudoku);
        }
        /// <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>
        /// 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();
        }
示例#10
0
        /// <summary>
        /// Creates a new <see cref="SudokuPuzzle"/> that is a copy of the current instance.
        /// </summary>
        /// <returns>A new <see cref="SudokuPuzzle"/> that is a copy of this instance.</returns>
        public Object Clone()
        {
            SudokuPuzzle clone = new SudokuPuzzle(this.Size, this.Difficulty);

            for (int i = 0; i < this.Size; i++)
            {
                for (int j = 0; j < this.Size; j++)
                {
                    clone.Cells[i, j] = (SudokuCell)this.Cells[i, j].Clone();
                }
            }

            return(clone);
        }
        /// <summary>
        /// Parses the text representing a single <see cref="SudokuPuzzle"/>.
        /// </summary>
        /// <param name="s">The text to parse.</param>
        /// <returns>A <see cref="SudokuPuzzle"/> representation of <c><paramref name="s"/></c>.</returns>
        /// <exception cref="ArgumentNullException"><c><paramref name="s"/></c> is <c>null</c>.</exception>
        /// <exception cref="FormatException"><c><paramref name="s"/></c> is not in the correct format.</exception>
        public static SudokuPuzzle Deserialize(String s)
        {
            if (s is null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            String[] split = s.Split(',');

            if (split.Length != 5)
            {
                throw new FormatException();
            }

            try
            {
                int size    = Int32.Parse(split[0]);
                int squared = size * size;

                if (!SudokuPuzzle.VerifySize(size))
                {
                    throw new FormatException();
                }

                SudokuDifficulty difficulty = (SudokuDifficulty)Enum.Parse(typeof(SudokuDifficulty), split[1], true);
                int[]            numbers    = new int[squared], solutions = new int[squared];
                bool[]           readOnly   = new bool[squared];

                if (split[2].Length != squared || split[3].Length != squared || split[4].Length != squared)
                {
                    throw new FormatException();
                }

                for (int i = 0; i < squared; i++)
                {
                    numbers[i]   = split[2][i] - '0';
                    solutions[i] = split[3][i] - '0';
                    readOnly[i]  = split[3][i] == '1';
                }

                SudokuPuzzle puzzle = SudokuPuzzle.Parse(size, difficulty, numbers, solutions, readOnly);
                puzzle.ResetPossible();
                return(puzzle);
            }

            catch
            {
                throw new FormatException();
            }
        }
示例#12
0
 public void UpdatePuzzle()
 {
     _puzzle = new SudokuPuzzle();
     for (int i = 0; i < 9; ++i)
         for (int j = 0; j < 9; ++j)
             try
             {
                 if (this.Controls[j * 9 + i].Text.Length != 0)
                     _puzzle[i, j].Value = int.Parse(this.Controls[j * 9 + i].Text);
                 else
                     _puzzle[i, j].Value = 0;
             }
             catch { _puzzle[i, j].Value = 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();
        }
        private void Create_Sudoku(int numCells)
        {
            puzzle = new SudokuPuzzle(9);
            puzzle.GenerateSudoku(numCells);

            for (var startingCell = 0; startingCell < 81; startingCell++)
            {
                if (puzzle.Cells[startingCell].Count == 1)
                {
                    _borders[startingCell].Background.ClearValue(SolidColorBrush.ColorProperty);
                    _values[startingCell].Text = puzzle.Cells[startingCell][0].ToString();
                    _values[startingCell].Foreground = new SolidColorBrush(Colors.DodgerBlue);
                }

            }

        }
        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));
        }
        /// <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();
        }
示例#17
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Generate a new puzzle. Can take rather long (up to half a minute or so)
            //Stopwatch stopwatch = new Stopwatch();
            //stopwatch.Start();
            //SudokuPuzzle sudoku = SudokuPuzzle.Generate();
            //stopwatch.Stop();

            //int hints = sudoku.Grid.Count(kvp => kvp.Value.IsSolved);
            //MessageBox.Show("Generated the puzzle in " + stopwatch.ElapsedMilliseconds + " milliseconds."
            //	+ "\nContains " + hints + " hints.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // Some test puzzles:
            SudokuPuzzle sudoku = new SudokuPuzzle();

            //sudoku.Fill("200807000 070610029 400903010 891000005 020109080 700000961 060305008 930068050 000201004");
            //sudoku.Fill("004090800 780020000 090008001 000600084 038000590 940001000 200300070 000060035 003070600");
            //sudoku.Fill("000400300 000801005 480000090 708000010 009207500 060000709 090000026 300504000 007009000");

            // Naked Sets, Intersection and Colors test
            //sudoku.Fill("000200000 065000900 070006040 000001005 710000009 009020010 001000700 087304020 000060094");

            // From http://www.forbeginners.info/sudoku-puzzles/extreme-1.htm
            sudoku.Fill("009748000 700000000 020109000 007000240 064010590 098000300 000803020 000000006 000275900");
            // From http://www.forbeginners.info/sudoku-puzzles/extreme-20.htm
            //sudoku.Fill("600000040 005002007 729000003 090040001 000060000 400080070 300000165 200400800 050000004");

            // From Folia; has two solutions
            //sudoku.Fill("026005073 050040286 730000000 000078009 180000307 079000040 200500600 008730004 000002005");

            // Put the unsolved sudoku on the left grid
            Form1 form = new Form1();
            form.UnsolvedGrid.Initialize(sudoku);

            // Simulate a click on the solve button to solve it
            form.button1_Click(null, EventArgs.Empty);

            Application.Run(form);
        }
示例#18
0
        private async Task StartNewGame() // Creates new game and starts the stopwatch
        {
            stopwatch.Reset();
            // Clear the value in every cell
            ResetUI();

            // Generate new game
            puzzle = new SudokuPuzzle();
            await Task.Run(() => puzzle.GenerateGame(36));    //generate game with 36 blanks

            ExecuteForEvery((i, j) =>
            {
                if (puzzle.sudokuPuzzle[i, j].Value != 0)
                {
                    cells[i, j].IsLocked = true;
                }
            });
            UpdateUI();
            stopwatch.Restart();
        }
示例#19
0
        /// <summary>
        /// Determines whether the specified <c><paramref name="sudoku"/></c> is equal to the current <see cref="SudokuPuzzle"/>.
        /// </summary>
        /// <param name="sudoku">The puzzle to compare with the current <see cref="SudokuPuzzle"/>.</param>
        /// <returns><c>true</c> if <c><paramref name="sudoku"/></c> is equal to the current <see cref="SudokuPuzzle"/>; otherwise, <c>false</c>.</returns>
        public bool Equals(SudokuPuzzle sudoku)
        {
            if (sudoku is null || this.Size != sudoku.Size)
            {
                return(false);
            }

            for (int i = 0; i < this.Size; i++)
            {
                for (int j = 0; j < this.Size; j++)
                {
                    if (this.Cells[i, j].Number != sudoku.Cells[i, j].Number)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
示例#20
0
        internal static SudokuPuzzle Parse(int size, SudokuDifficulty difficulty, int[] numbers, int[] solutions, bool[] readOnly)
        {
            SudokuPuzzle puzzle = new SudokuPuzzle(size, difficulty);

            for (int i = 0; i < size; i++)
            {
                int row = i * size;

                for (int j = 0; j < size; j++)
                {
                    int        index = row + j;
                    SudokuCell cell  = puzzle.Cells[i, j];
                    cell.Number     = numbers[index];
                    cell.Solution   = solutions[index];
                    cell.IsReadOnly = readOnly[index];
                }
            }

            return(puzzle);
        }
示例#21
0
        /// <summary>
        /// Converts the string representation to its <see cref="SudokuPuzzle"/> equivalent.
        /// </summary>
        /// <param name="s">A string containing a puzzle to convert.</param>
        /// <param name="difficulty">An optional difficulty to associate with the <see cref="SudokuPuzzle"/>.</param>
        /// <returns>A <see cref="SudokuPuzzle"/> equivalent to the puzzle contained in <c><paramref name="s"/></c>.</returns>
        /// <exception cref="ArgumentNullException"><c><paramref name="s"/></c> is <c>null</c>.</exception>
        /// <exception cref="FormatException"><c><paramref name="s"/></c> is not in the correct format.</exception>
        public static SudokuPuzzle Parse(String s, SudokuDifficulty difficulty = SudokuDifficulty.None)
        {
            if (s is null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            s = Regex.Replace(s, @"[^0-9]", "");
            int size = (int)Math.Sqrt(s.Length);

            if (!SudokuPuzzle.VerifySize(size))
            {
                throw new FormatException();
            }

            SudokuPuzzle sudoku;

            try
            {
                sudoku = new SudokuPuzzle(size, difficulty);
            }

            catch
            {
                throw new FormatException();
            }

            for (int i = 0; i < size; i++)
            {
                int currentRow = i * size;

                for (int j = 0; j < size; j++)
                {
                    sudoku[i, j] = s[currentRow + j] - '0';
                }
            }

            return(sudoku);
        }
        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);
        }
        /// <summary>
        /// Converts a specified <see cref="SudokuPuzzle"/> into a string.
        /// </summary>
        /// <param name="sudoku">The <see cref="SudokuPuzzle"/> to convert.</param>
        /// <returns>The standard format string representation of <c><paramref name="sudoku"/></c>.</returns>
        /// <exception cref="ArgumentNullException"><c><paramref name="sudoku"/></c> is <c>null</c>.</exception>
        public static String Seralize(SudokuPuzzle sudoku)
        {
            if (sudoku is null)
            {
                throw new ArgumentNullException(nameof(sudoku));
            }

            StringBuilder numberBuilder   = new StringBuilder();
            StringBuilder solutionBuilder = new StringBuilder();
            StringBuilder readOnlyBuilder = new StringBuilder();

            for (int i = 0; i < sudoku.Size; i++)
            {
                for (int j = 0; j < sudoku.Size; j++)
                {
                    numberBuilder.Append(sudoku[i, j]);
                    solutionBuilder.Append(sudoku.GetSolution(i, j));
                    readOnlyBuilder.Append(sudoku.CheckReadOnly(i, j) ? 1 : 0);
                }
            }

            return(String.Join(",", sudoku.Size, (int)sudoku.Difficulty, numberBuilder, solutionBuilder, readOnlyBuilder));
        }
示例#24
0
        public SudokuGrid(SudokuPuzzle puzzle, SudokuPuzzleLoadOptions loadOptions)
        {
            InitializeComponent();

            this._puzzle = puzzle;
            this._zones = new SudokuZone[puzzle.Rank, puzzle.Rank];

            // Load the UI
            StackPanel gridStackPanel = new StackPanel() { Orientation = Orientation.Vertical };

            for (int i = 0; i < puzzle.Rank; i++)
            {
                StackPanel rowStackPanel = new StackPanel() { Orientation = Orientation.Horizontal };

                for (int j = 0; j < puzzle.Rank; j++)
                {
                    SudokuZone zone = new SudokuZone(this, i, j);
                    this._zones[i, j] = zone;
                    rowStackPanel.Children.Add(zone);
                }

                gridStackPanel.Children.Add(rowStackPanel);
            }

            this.SudokuZoneContainer.Child = gridStackPanel;

            // Load the puzzle into the UI
            switch (loadOptions)
            {
                case SudokuPuzzleLoadOptions.StartNew:
                    for (int i = 0; i < (this._puzzle.Rank * this._puzzle.Rank); i++)
                    {
                        for (int j = 0; j < (this._puzzle.Rank * this._puzzle.Rank); j++)
                        {
                            int value = int.Parse(this._puzzle.Format[i].Split(new char[] { ',' })[j].ToString());

                            SudokuCell cell = this.GetCell(i, j);
                            if (value != 0)
                            {
                                cell.Value = value;
                                cell.State = SudokuCell.CellState.Locked;
                            }
                        }
                    }
                    break;

                case SudokuPuzzleLoadOptions.LoadSavedGame:
                    for (int i = 0; i < (this._puzzle.Rank * this._puzzle.Rank); i++)
                    {
                        for (int j = 0; j < (this._puzzle.Rank * this._puzzle.Rank); j++)
                        {
                            int value = int.Parse(this._puzzle.SaveState[i].Split(new char[] { ',' })[j].ToString());
                            int formatValue = int.Parse(this._puzzle.Format[i].Split(new char[] { ',' })[j].ToString());

                            SudokuCell cell = this.GetCell(i, j);
                            if (value != 0)
                            {
                                if (value != formatValue)
                                {

                                        cell.Value = value;
                                        cell.State = SudokuCell.CellState.Editable;
                                }
                                else
                                {
                                        cell.Value = value;
                                        cell.State = SudokuCell.CellState.Locked;
                                }
                            }
                        }
                    }
                    break;

                case SudokuPuzzleLoadOptions.LoadSolution:
                    for (int i = 0; i < (this._puzzle.Rank * this._puzzle.Rank); i++)
                    {
                        for (int j = 0; j < (this._puzzle.Rank * this._puzzle.Rank); j++)
                        {
                            int value = int.Parse(this._puzzle.Solution[i].Split(new char[] { ',' })[j].ToString());
                            int formatValue = int.Parse(this._puzzle.Format[i].Split(new char[] { ',' })[j].ToString());

                            SudokuCell cell = this.GetCell(i, j);
                            if (value != 0)
                            {
                                if (value != formatValue)
                                {
                                    cell.Value = value;
                                    cell.State = SudokuCell.CellState.Editable;
                                }
                                else
                                {
                                    cell.Value = value;
                                    cell.State = SudokuCell.CellState.Locked;
                                }
                            }
                        }
                    }
                    break;

                case SudokuPuzzleLoadOptions.EditMode:
                    for (int i = 0; i < (this._puzzle.Rank * this._puzzle.Rank); i++)
                    {
                        for (int j = 0; j < (this._puzzle.Rank * this._puzzle.Rank); j++)
                        {
                            int value = int.Parse(this._puzzle.Format[i].Split(new char[] { ',' })[j].ToString());

                            SudokuCell cell = this.GetCell(i, j);
                            if (value != 0)
                            {
                                cell.Value = value;
                            }
                        }
                    }
                    break;

                default:
                    // Do not load anything
                    break;
            }
        }
示例#25
0
        public SudokuGrid(SudokuPuzzle puzzle, SudokuPuzzleLoadOptions loadOptions, TextBlock availableValuesTextBlock, TextBlock possibleValuesTextBlock)
            : this(puzzle, loadOptions)
        {
            this._availableValuesTextBlock = availableValuesTextBlock;
            this._possibleValuesTextBlock = possibleValuesTextBlock;

            this.CheckAvailableValues();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SudokuSolver"/> class with the specified <see cref="T:Sudoku.Sudoku"/> puzzle.
 /// </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 SudokuSolver(SudokuPuzzle sudoku)
 {
     this.Moves  = new List <SudokuMove>();
     this.Random = new Random();
     this.Sudoku = sudoku ?? throw new ArgumentNullException(nameof(sudoku));
 }
示例#27
0
        private SudokuPuzzle internalGenerate(int desiredRatingLevel, long initialSeed)
        {
            // validate the passed-in desired rating level:
            if ((desiredRatingLevel < 0) && (desiredRatingLevel >= RatingsByLevel.Length))
                desiredRatingLevel = 0;

            RatingLimits RL = RatingsByLevel[desiredRatingLevel];

            SudokuPuzzle p = new SudokuPuzzle();
            p.DesiredRatingLevel = desiredRatingLevel;
            p.Seed = initialSeed;
            p.NumHints = 0;

            // Find a Sudoku having a rating within a specified rating interval.
            // Do it by generating multiple samples and examining them.
            // Continue until an appropriate puzzle is found.

            // Sometimes we need to iterate over multiple sets of puzzles.
            // Iteration doesn't make sense though, if there is an initialSeed
            // provided. So we set the loopLimit appropriately.
            int loopLimit = (initialSeed == 0) ? MaxGenerateLoops : 1;

            for (int tries = 0; tries < loopLimit; tries++, System.Threading.Thread.Sleep(20))
            {
                long actualSeed = (initialSeed == 0) ? System.DateTime.Now.Ticks : initialSeed;

                String[] puzzles = _generator.GeneratePuzzleSet((int)actualSeed, SampleSetSize);
                for (int i = 0; i < SampleSetSize; i++)
                {
                    // get the rating
                    long rating = _generator.Rate(puzzles[i].Replace("\n", "").Trim());

                    if ((i == 0) || RL.Delta(rating) < p.Delta)
                    {
                        p.ActualRating = rating;
                        p.StringRep = puzzles[i];
                        p.Seed = actualSeed;
                        p.Delta = RL.Delta(rating);
                    }
                }
                if (RL.WithinRange(p.ActualRating)) return p;
            }

            return p;
        }
示例#28
0
 public void LoadPuzzle(SudokuPuzzle puzzle, SudokuPuzzleLoadOptions loadOptions)
 {
     Global.Game.Grid = new SudokuGrid(puzzle, loadOptions, this.RemainingNumbersTextBlock, this.PossibleValuesTextBlock) { HorizontalAlignment = System.Windows.HorizontalAlignment.Center };
     this.SudokuGridContainer.Child = Global.Game.Grid;
 }