コード例 #1
0
        public void SetAllPossibleValues(int row, int col, SudokuCell cell = null)
        {
            var currentCellPossibleValues = this.sudoku[row, col].PossibleValues;

            var valuesOnRow = GetValuesOnRow(row, cell);
            var valuesOnCol = GetValuesOnCol(col, cell);

            var startRow = (row / 3) * 3;
            var startCol = (col / 3) * 3;

            var valuesOnBox = GetValuesInBox(startRow, startCol, cell);

            foreach (var item in valuesOnBox)
            {
                currentCellPossibleValues.Remove(item);
            }

            foreach (var item in valuesOnCol)
            {
                currentCellPossibleValues.Remove(item);
            }

            foreach (var item in valuesOnRow)
            {
                currentCellPossibleValues.Remove(item);
            }
        }
コード例 #2
0
        private void InitCells(SudokuGrid grid)
        {
            CurrentCell         = new SudokuCell(FirstCellRowPosition, FirstCellColPosition);
            CurrentCellRowIndex = 0;
            CurrentCellColIndex = 0;

            const int SudokuDim = SudokuGrid.SudokuDimension;

            cells = new SudokuCell[SudokuDim, SudokuDim];
            int       currWindowRowPos = GameWindow.FirstCellRowPosition;
            int       currWindowColPos = GameWindow.FirstCellColPosition;
            const int RowIncrement     = GameWindow.CellPositionRowIncrements;
            const int ColIncrement     = GameWindow.CellPositionColIncrements;

            for (int row = 0; row < SudokuDim; row++)
            {
                for (int col = 0; col < SudokuDim; col++)
                {
                    cells[row, col]   = new SudokuCell(grid[row, col], grid.IsEditable(row, col), currWindowRowPos, currWindowColPos);
                    currWindowColPos += ColIncrement;
                }
                currWindowColPos  = GameWindow.FirstCellColPosition;
                currWindowRowPos += RowIncrement;
            }

            menuCells = new MenuCell[MenuItemLabels.Length];
            for (int item = 0; item < menuCells.Length; item++)
            {
                menuCells[item] = new MenuCell(MenuItemsCellRowPosition, MenuItemsCellColPositions[item], MenuItemLabels[item]);
            }
            RedrawCells();
        }
コード例 #3
0
ファイル: SudokuZone.xaml.cs プロジェクト: delner/sudoku
        public SudokuZone()
        {
            InitializeComponent();

            this._grid = null;
            this._cells = new SudokuCell[3, 3];
            this._row = 0;
            this._column = 0;

            StackPanel zoneStackPanel = new StackPanel() { Orientation = Orientation.Vertical };

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

                for (int j = 0; j < 3; j++)
                {
                    SudokuCell cell = new SudokuCell();
                    this._cells[i, j] = cell;
                    rowStackPanel.Children.Add(cell);
                }

                zoneStackPanel.Children.Add(rowStackPanel);
            }

            this.SudokuCellContainer.Child = zoneStackPanel;
        }
コード例 #4
0
ファイル: SudokuZone.xaml.cs プロジェクト: delner/sudoku
        public SudokuZone(SudokuGrid grid, int row, int col)
        {
            InitializeComponent();

            this._grid = grid;
            this._cells = new SudokuCell[grid.Puzzle.Rank, grid.Puzzle.Rank];
            this._row = row;
            this._column = col;

            StackPanel zoneStackPanel = new StackPanel() { Orientation = Orientation.Vertical };

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

                for (int j = 0; j < grid.Puzzle.Rank; j++)
                {
                    SudokuCell cell = new SudokuCell(this, i, j);
                    this._cells[i, j] = cell;
                    rowStackPanel.Children.Add(cell);
                }

                zoneStackPanel.Children.Add(rowStackPanel);
            }

            this.SudokuCellContainer.Child = zoneStackPanel;
        }
コード例 #5
0
ファイル: Sudoku.cs プロジェクト: dixitsandeep/sudoku
        private double CalculateDifficulty()
        {
            List <int> topN = new List <int>(10);

            topN.Add(0);

            for (int rowIndex = 0; rowIndex <= 8; rowIndex++)
            {
                for (int colIndex = 0; colIndex <= 8; colIndex++)
                {
                    SudokuCell cell = sudokuCells[rowIndex][colIndex];

                    int cellDifficulty = (int)cell.SolvingDifficulty;

                    if (cellDifficulty > topN.Min())
                    {
                        if (topN.Count < topN.Capacity)
                        {
                            topN.Add(cellDifficulty);
                        }
                        else
                        {
                            topN.Remove(topN.Min());
                            topN.Add(cellDifficulty);
                        }
                    }
                }
            }

            double topNAverage = topN.Average();



            return(topNAverage);
        }
コード例 #6
0
ファイル: Sudoku.cs プロジェクト: dixitsandeep/sudoku
        private void EliminatePossibilitiesFromUnsetCells(SudokuGroup sudokuGroup)
        {
            HashSet <int> allNumbersPresentInGroup = new HashSet <int>();

            for (int cellIndex = 0; cellIndex <= 8; cellIndex++)
            {
                int cellValue = sudokuGroup.Cells[cellIndex].Value;

                if (cellValue != 0)
                {
                    allNumbersPresentInGroup.Add(cellValue);
                }
            }



            for (int cellIndex = 0; cellIndex <= 8; cellIndex++)
            {
                int cellValue = sudokuGroup.Cells[cellIndex].Value;

                if (cellValue == 0)
                {
                    SudokuCell cell = sudokuGroup.Cells[cellIndex];
                    cell.RemainingPossibilities.ExceptWith(allNumbersPresentInGroup);

                    if (cell.RemainingPossibilities.Count == 1)
                    {
                        cell.Value             = cell.RemainingPossibilities.First();
                        cell.SolvingDifficulty = SolvingDifficulty.Easy;
                    }
                }
            }
        }
コード例 #7
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();
        }
コード例 #8
0
ファイル: SudokuCell.cs プロジェクト: zainabaaj/sudoku-game
 public bool HasSamePositionAs(SudokuCell other)
 {
     if (this.windowRowPosition == other.windowRowPosition && this.windowColPosition == other.windowColPosition)
     {
         return(true);
     }
     return(false);
 }
コード例 #9
0
 public bool HasSamePositionAs(SudokuCell other)
 {
     if (this.windowRowPosition == other.windowRowPosition && this.windowColPosition == other.windowColPosition)
     {
         return true;
     }
     return false;
 }
コード例 #10
0
        private void EnterTextBox(object sender, MouseEventArgs e)
        {
            ColorAnimation animation = new ColorAnimation();
            var            textBox   = sender as TextBox;

            var sudokuDifficulty = new SudokuDifficulty();
            var sudoku           = new SudokuCell[9, 9];

            if ((FindName("checkBoxHints") as CheckBox).IsChecked == true)
            {
                if (textBox.IsReadOnly == false && lastSudokuDifficulty != 0 && textBox.Text == string.Empty)
                {
                    try
                    {
                        var counter  = 0;
                        var inputRow = 0;
                        var inputCol = 0;
                        for (int row = 0; row < 9; row++)
                        {
                            for (int col = 0; col < 9; col++)
                            {
                                var box = this.FindName("TextBox" + counter) as TextBox;
                                sudoku[row, col] = new SudokuCell(row, col);
                                if (box.Text != string.Empty)
                                {
                                    sudoku[row, col].Value = int.Parse(box.Text);
                                }
                                if ("TextBox" + counter == textBox.Name)
                                {
                                    inputCol = col;
                                    inputRow = row;
                                }
                                counter++;
                            }
                        }
                        var outputList = sudokuDifficulty.GetAllPossibleNumbers(inputRow, inputCol, sudoku).PossibleValues;

                        var result = string.Join(" ", outputList);

                        var toolTip = new ToolTip();
                        toolTip.Background = new SolidColorBrush(Color.FromRgb(255, 250, 252));
                        toolTip.Content    = string.Format("You can put those numbers: {0}!", result);
                        textBox.ToolTip    = toolTip;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }



            animation.To       = Color.FromRgb(227, 232, 234);
            animation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
            textBox.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
        }
コード例 #11
0
        private HashSet <int> GetValuesOnRow(int row, SudokuCell cell)
        {
            var result = new HashSet <int>();

            for (int col = 0; col < 9; col++)
            {
                if (this.sudoku[row, col].Value != 0 && !this.sudoku[row, col].Equals(cell))
                {
                    result.Add(this.sudoku[row, col].Value);
                }
            }
            return(result);
        }
コード例 #12
0
ファイル: Sudoku.cs プロジェクト: dixitsandeep/sudoku
        private Sudoku()
        {
            for (int i = 0; i <= 8; i++)
            {
                sudokuCells[i]   = new SudokuCell[9];
                sudokuRows[i]    = new SudokuGroup(i);
                sudokuColumns[i] = new SudokuGroup(i);
                sudokuBoxes[i]   = new SudokuGroup(i);
            }

            //1. Initialize Cells and create row view

            for (int rowIndex = 0; rowIndex <= 8; rowIndex++)
            {
                for (int colIndex = 0; colIndex <= 8; colIndex++)
                {
                    sudokuCells[rowIndex][colIndex]         = new SudokuCell(rowIndex, colIndex);
                    sudokuRows[rowIndex].Cells[colIndex]    = sudokuCells[rowIndex][colIndex];
                    sudokuColumns[colIndex].Cells[rowIndex] = sudokuCells[rowIndex][colIndex];
                }
            }


            //2. create box view
            //([0] ,[1] , [2])
            //([3] ,[4] , [5])
            //([6] ,[7] , [8])

            for (int boxIndex = 0; boxIndex <= 8; boxIndex++)
            {
                for (int cellIndexInABox = 0; cellIndexInABox <= 8; cellIndexInABox++)
                {
                    //Box,cell 0,0 == Row Col >0,0
                    //1,0 ==>  0,3
                    //2,2 ==>0,8
                    //3,3 ==>4,0
                    //8,0 ==>6,6
                    //8,8 ==>8,8

                    int firtCellRowIndex = (boxIndex - (boxIndex % 3));
                    int firtCellColIndex = (boxIndex % 3) * 3;

                    int rowIndex = firtCellRowIndex + cellIndexInABox / 3;
                    int colIndex = firtCellColIndex + cellIndexInABox % 3;

                    sudokuBoxes[boxIndex].Cells[cellIndexInABox] = sudokuCells[rowIndex][colIndex];
                }
            }

            //MessageBox.Show(message);
        }
コード例 #13
0
ファイル: SudokuSolver.cs プロジェクト: Cecosam/Sudoku-API
        private SudokuCell[,] CloneSudoku(SudokuCell[,] sudoku)
        {
            var result = new SudokuCell[9, 9];

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    result[i, j]       = new SudokuCell(i, j);
                    result[i, j].Value = sudoku[i, j].Value;
                }
            }
            return(result);
        }
コード例 #14
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)
            {
            }
        }
コード例 #15
0
        private HashSet <int> GetValuesInBox(int startRow, int startCol, SudokuCell cell)
        {
            var result = new HashSet <int>();

            for (int row = startRow; row < startRow + 3; row++)
            {
                for (int col = startCol; col < startCol + 3; col++)
                {
                    if (this.sudoku[row, col].Value != 0 && !this.sudoku[row, col].Equals(cell))
                    {
                        result.Add(this.sudoku[row, col].Value);
                    }
                }
            }
            return(result);
        }
コード例 #16
0
ファイル: SudokuSolver.cs プロジェクト: Cecosam/Sudoku-API
        public bool CheckIfSudokuIsValid(SudokuCell[,] sudokuToSolve)
        {
            if (sudokuToSolve.GetLength(0) != 9 || sudokuToSolve.GetLength(1) != 9)
            {
                return(false);
            }

            int minimumOfSudokuClues = 17;
            int countOfClues         = 0;

            InitializeSudoku();
            this.fixedSudokuNumbers = new bool[9, 9];

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (sudokuToSolve[i, j] == null)
                    {
                        sudokuToSolve[i, j] = new SudokuCell(i, j);
                    }
                    if (sudokuToSolve[i, j].Value != 0)
                    {
                        this.sudoku[i, j].Value       = sudokuToSolve[i, j].Value;
                        this.fixedSudokuNumbers[i, j] = true;
                        countOfClues++;
                    }
                }
            }

            if (countOfClues < minimumOfSudokuClues)
            {
                this.sudoku             = null;
                this.fixedSudokuNumbers = null;
                return(false);
            }

            if (!ValidateSudokuNumbers())
            {
                this.sudoku             = null;
                this.fixedSudokuNumbers = null;
                return(false);
            }
            return(true);
        }
コード例 #17
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);
        }
コード例 #18
0
        private void createCells()
        {
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    cells[i, j]           = new SudokuCell();
                    cells[i, j].Font      = new Font(SystemFonts.DefaultFont.FontFamily, 20);
                    cells[i, j].Size      = new Size(60, 60);
                    cells[i, j].ForeColor = SystemColors.ControlDarkDark;
                    cells[i, j].Location  = new Point(i * 50, j * 50);
                    cells[i, j].BackColor = ((i / 3) + (j / 3)) % 2 == 0 ? SystemColors.Control : Color.YellowGreen;
                    cells[i, j].FlatStyle = FlatStyle.Flat;
                    cells[i, j].FlatAppearance.BorderColor = Color.Black;
                    cells[i, j].X = i;
                    cells[i, j].Y = j;

                    cells[i, j].KeyPress += cell_keyPressed;
                    panel1.Controls.Add(cells[i, j]);
                }
            }
        }
コード例 #19
0
ファイル: SudokuForm.cs プロジェクト: MalgorzataBorowy/Sudoku
        private void CreateCells()
        {
            ExecuteForEvery((i, j) =>
            {
                // Create 81 cells for with styles and locations based on the index
                cells[i, j]           = new SudokuCell();
                cells[i, j].Font      = new Font(SystemFonts.DefaultFont.FontFamily, 20);
                cells[i, j].Size      = new Size(40, 40);
                cells[i, j].Location  = new Point(i * 40, j * 40);
                cells[i, j].BackColor = ((i / 3) + (j / 3)) % 2 == 0 ? SystemColors.Control : Color.LightSeaGreen;
                cells[i, j].ForeColor = ((i / 3) + (j / 3)) % 2 == 0 ? Color.Black : Color.White;
                cells[i, j].FlatStyle = FlatStyle.Flat;
                cells[i, j].FlatAppearance.BorderColor = Color.Teal;
                cells[i, j].FlatAppearance.BorderSize  = 1;
                cells[i, j].X = i;
                cells[i, j].Y = j;

                // Assign key press event for each cells
                cells[i, j].KeyPress += cell_keyPressed;

                panel1.Controls.Add(cells[i, j]);
            });
        }
コード例 #20
0
        /// <summary>
        /// Creates a list of Sudoku Cells and determines each cell's sector,
        /// index, row and column values. List of available integer values
        /// and the initial value of Value property also set in that function.
        /// </summary>
        private void InitSudokuCells()
        {
            SudokuCell sudokuCell = null;

            int row = 0, column = 0, sector = 0, count = 1, startSector = 0;

            for (int i = 0; i < _gridSize; i++)
            {
                sudokuCell = new SudokuCell(_rowSize);

                if (i % _rowSize == 0 && i > 0)
                {
                    column = 0;
                    row++;

                    if (row % _sectorRowSize != 0 && count <= _sectorRowSize)
                        sector = startSector;
                    else
                    {
                        startSector = sector;
                        count = 1;
                    }
                }

                if (column % _sectorRowSize == 0)
                    sector++;

                sudokuCell.Value = 0;
                sudokuCell.Column = column;
                sudokuCell.Row = row;
                sudokuCell.Sector = sector;
                sudokuCell.Index = i;

                column++;

                _sudokuCellList.Add(sudokuCell);
            }
        }
コード例 #21
0
 private bool IfExistsInSector(SudokuCell sudokuCell)
 {
     return _sudokuCellList.Count(x => x.Value > 0 && x.Index != sudokuCell.Index && x.Sector == sudokuCell.Sector && x.Value == sudokuCell.Value) > 0;
 }
コード例 #22
0
ファイル: Sudoku.cs プロジェクト: dixitsandeep/sudoku
        private bool SolveByTryingPossibilities()
        {
            if (!IsAValidState())
            {
                return(false);
            }

            int unsolvedCells = CountUnsolvedCells();

            if (unsolvedCells == 0)
            {
                return(Solved);
            }


            SudokuCell[] linearArray = new SudokuCell[81];

            for (int rowIndex = 0; rowIndex <= 8; rowIndex++)
            {
                for (int colIndex = 0; colIndex <= 8; colIndex++)
                {
                    linearArray[rowIndex * 9 + colIndex] = sudokuCells[rowIndex][colIndex];
                }
            }
            //Sorted array by remaining possibilities.
            Array.Sort(linearArray);



            foreach (var cell in linearArray)
            {
                int rowIndex = cell.RowIndex;
                int colIndex = cell.ColIndex;

                if (cell.Value == 0)
                {
                    var remainingDigitsOnThisCell = cell.RemainingPossibilities;

                    if (remainingDigitsOnThisCell.Count == 0)
                    {
                        Logger.WriteLine("Invalid situation. remainingDigitsOnThisCell.Count == 0 ", _cloningDepth);
                        return(false);
                    }

                    //if (cloningDepth == 0)
                    {
                        Logger.WriteLine($"Evaluating Cell@{cell} ", _cloningDepth);
                        Logger.WriteLine(ToStringFormatted(), _cloningDepth);
                    }

                    foreach (var possibility in remainingDigitsOnThisCell)
                    {
                        //Set this possibility and try to solve.
                        Sudoku clone = new Sudoku(this.ToString());
                        clone._cloningDepth = this._cloningDepth + 1;

                        clone.sudokuCells[rowIndex][colIndex].Value = possibility;

                        if (clone.Solve())
                        {
                            //if (cloningDepth == 0)
                            {
                                Logger.WriteLine($"Valid Solution found for Cell@{cell}  new Value {possibility}", _cloningDepth);
                                Logger.WriteLine($"\n{clone.ToStringFormatted()}", _cloningDepth);
                            }

                            cell.SolvingDifficulty = SolvingDifficulty.MaxDifficulty;
                            cell.Value             = possibility;

                            CopyUnSolvedCellsFromSolution(clone);

                            return(Solved);
                        }
                    }

                    if (_cloningDepth == 0)
                    {
                        throw new Exception("No possibility worked. Root problem is not right");
                    }

                    Logger.WriteLine($"No possibility worked for  Cell@{cell}. Impossible situation. Should be backtraced.", _cloningDepth);

                    return(Notsolved);
                }
            }



            return(Notsolved);
        }
コード例 #23
0
        private void CheckIfSudokuIsValid(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))
            {
                var inputCells = new bool[9, 9];
                var sudoku     = new SudokuCell[9, 9];

                counter = 0;
                for (int row = 0; row < 9; row++)
                {
                    for (int col = 0; col < 9; col++)
                    {
                        var element = this.FindName("TextBox" + counter) as TextBox;
                        int number;
                        var isParsed = int.TryParse(element.Text, out number);
                        sudoku[row, col] = new SudokuCell(row, col);
                        if (isParsed && element.IsReadOnly == false)
                        {
                            sudoku[row, col].Value = number;
                        }
                        else
                        {
                            sudoku[row, col].Value = number;
                            inputCells[row, col]   = true;
                        }
                        counter++;
                    }
                }

                var listWithCellsWithError = sudokuSolver.GetAllCellsWithError(sudoku, inputCells);

                ColorTheCellsWithError(listWithCellsWithError);

                MessageBox.Show("You have some errors!");
                return;
            }

            try
            {
                sudokuToSolve = sudokuSolver.SolveSudoku(sudokuToSolve);
            }
            catch (ArgumentException)
            {
                var inputCells = new bool[9, 9];
                var sudoku     = new SudokuCell[9, 9];

                counter = 0;
                for (int row = 0; row < 9; row++)
                {
                    for (int col = 0; col < 9; col++)
                    {
                        var element = this.FindName("TextBox" + counter) as TextBox;
                        int number;
                        var isParsed = int.TryParse(element.Text, out number);
                        sudoku[row, col] = new SudokuCell(row, col);
                        if (isParsed && element.IsReadOnly == false)
                        {
                            sudoku[row, col].Value = number;
                        }
                        else
                        {
                            sudoku[row, col].Value = number;
                            inputCells[row, col]   = true;
                        }
                        counter++;
                    }
                }

                var listWithCellsWithError = sudokuSolver.GetAllCellsWithError(sudoku, inputCells, false);

                ColorTheCellsWithError(listWithCellsWithError);
                MessageBox.Show("You have some errors!");
                return;
            }

            MessageBox.Show("You are doing great!");
        }
コード例 #24
0
 /// <summary>
 /// Checks sudoku constraints for the Sudoku Cell.
 /// Constraints are;
 ///     1. The value must be unique in row
 ///     2. The value must be unique in sector
 ///     3. The value must be unique in column
 /// </summary>
 /// <param name="sudokuCell"></param>
 /// <returns></returns>
 private bool CheckConstraints(SudokuCell sudokuCell)
 {
     return !IfExistsInSector(sudokuCell) && !IfExistsInRow(sudokuCell) && !IfExistsInColumn(sudokuCell);
 }
コード例 #25
0
ファイル: Sudoku.cs プロジェクト: kiddove/Sudoku
 // construction
 public Sudoku()
 {
     try
     {
         m_SudokuArray = new SudokuCell[m_iSize][];
         for (int i = 0; i < m_iSize; i++)
         {
             SudokuCell[] cells = new SudokuCell[m_iSize];
             for (int j = 0; j < m_iSize; j++)
             {
                 //cells[j] = new SudokuCell(i, j);
                 cells[j] = new SudokuCell();
             }
             m_SudokuArray[i] = cells;
         }
     }
     catch (Exception e)
     {
         Trace.WriteLine(e.Message);
     }
 }
コード例 #26
0
        /// <summary>
        /// A recursive function to genarete random values for each cell.
        /// In each recall, it is called with the previous SudokuCell in sudokuCellList.
        /// This function uses BackTrack Algorithm to fill each cell when a conflict occurs.
        /// </summary>
        /// <param name="sudokuCell">When NextIndex is null, current cell. Otherwise previous element that points to current cell</param>
        /// <param name="NextIndex">When this function is called recursively, NextIndex points the current cell's index.</param>
        private void GenerateRandomValue(SudokuCell sudokuCell, int? NextIndex = null)
        {
            do
            {
                if (sudokuCell.AvaliableIntList.Count(x => !x.Deleted) == 0)
                {
                    //We need a reset for the current cell because we used all available numbers
                    sudokuCell.Reset();

                    if (sudokuCell.Index == 0) // Worst case; we are starting to fill each cell from the beginning
                        GenerateRandomValue(_sudokuCellList[0], 1);
                    else
                        GenerateRandomValue(_sudokuCellList[sudokuCell.Index - 1], sudokuCell.Index);
                }

                sudokuCell.Value = PickNextAvailableValue(sudokuCell.AvaliableIntList);
            } while (!CheckConstraints(sudokuCell) || sudokuCell.Value == 0);
        }
コード例 #27
0
ファイル: Sudoku.cs プロジェクト: dixitsandeep/sudoku
        private void EliminatePreemptiveSetsInAGroup(SudokuGroup sudokuGroup)
        {
            int remainingPossibitySizeMax = 0;

            for (int cellIndex = 0; cellIndex <= 8; cellIndex++)
            {
                if (sudokuGroup.Cells[cellIndex].Value == 0)
                {
                    remainingPossibitySizeMax++;
                }
            }

            for (int remainingPossibitySize = 2; remainingPossibitySize <= remainingPossibitySizeMax; remainingPossibitySize++)
            {
                {
                    //1. Adjust possibilities for a Column

                    HashSet <int> preemptiveSet = new HashSet <int>();
                    HashSet <int> cellsWithCommonPossilities = new HashSet <int>();

                    for (int cellIndex = 0; cellIndex <= 8; cellIndex++)
                    {
                        var remainingPossibilitiesSet = sudokuGroup.Cells[cellIndex].RemainingPossibilities;


                        if (sudokuGroup.Cells[cellIndex].Value == 0 && remainingPossibilitiesSet.Count <= remainingPossibitySize)
                        {
                            var tempSet = new HashSet <int>(remainingPossibilitiesSet);

                            tempSet.UnionWith(preemptiveSet);

                            if (tempSet.Count <= remainingPossibitySize)
                            {
                                cellsWithCommonPossilities.Add(cellIndex);
                                preemptiveSet.UnionWith(remainingPossibilitiesSet);
                            }


                            if (cellsWithCommonPossilities.Count == preemptiveSet.Count)
                            {
                                break;
                            }
                        }
                    }

                    if (cellsWithCommonPossilities.Count == preemptiveSet.Count &&
                        preemptiveSet.Count > 0)
                    {
                        for (int cellIndex = 0; cellIndex <= 8; cellIndex++)
                        {
                            SudokuCell cell = sudokuGroup.Cells[cellIndex];
                            if (cell.Value == 0 && !cellsWithCommonPossilities.Contains(cellIndex))
                            {
                                //Reduce the possibilities.
                                cell.RemainingPossibilities.ExceptWith(preemptiveSet);


                                if (cell.RemainingPossibilities.Count == 1)
                                {
                                    cell.Value =
                                        cell.RemainingPossibilities.First();

                                    // Logger.WriteLine($"Solved a cell by preemptive Set. {cell.ColIndex},{cell.RowIndex}={cell.Value}");

                                    if (preemptiveSet.Count == 2)
                                    {
                                        cell.SolvingDifficulty = SolvingDifficulty.Medium;
                                    }
                                    if (preemptiveSet.Count == 3)
                                    {
                                        cell.SolvingDifficulty = SolvingDifficulty.Hard;
                                    }

                                    if (preemptiveSet.Count == 4)
                                    {
                                        cell.SolvingDifficulty = SolvingDifficulty.MaxDifficulty;
                                    }
                                }
                            }
                        }
                    }
                }

                remainingPossibitySize++;
            }
        }
コード例 #28
0
 private bool IfExistsInColumn(SudokuCell sudokuCell)
 {
     return _sudokuCellList.Count(x => x.Value > 0 && x.Index != sudokuCell.Index && x.Column == sudokuCell.Column && x.Value == sudokuCell.Value) > 0;
 }
コード例 #29
0
 private bool IfExistsInRow(SudokuCell sudokuCell)
 {
     return _sudokuCellList.Count(x => x.Value > 0 && x.Index != sudokuCell.Index && x.Row == sudokuCell.Row && x.Value == sudokuCell.Value) > 0;
 }
コード例 #30
0
        private void InitCells(SudokuGrid grid)
        {
            //Initialize and set highlighted cell.
            CurrentCell = new SudokuCell(FirstCellRowPosition, FirstCellColPosition);
            CurrentCellRowIndex = 0;
            CurrentCellColIndex = 0;

            //Initialize other number fields.
            const int SudokuDim = SudokuGrid.SudokuDimension;
            cells = new SudokuCell[SudokuDim,SudokuDim];
            int currWindowRowPos = GameWindow.FirstCellRowPosition;
            int currWindowColPos = GameWindow.FirstCellColPosition;
            const int RowIncrement = GameWindow.CellPositionRowIncrements;
            const int ColIncrement = GameWindow.CellPositionColIncrements;

            for (int row = 0; row < SudokuDim; row++)
            {
                for (int col = 0; col < SudokuDim; col++)
                {
                    cells[row, col] = new SudokuCell(grid[row, col], grid.IsEditable(row, col), currWindowRowPos, currWindowColPos);
                    currWindowColPos += ColIncrement;
                }
                currWindowColPos = GameWindow.FirstCellColPosition;
                currWindowRowPos += RowIncrement;
            }

            //Initialize menu items
            menuCells = new MenuCell[MenuItemLabels.Length];
            for (int item = 0; item < menuCells.Length; item++)
            {
                menuCells[item] = new MenuCell(MenuItemsCellRowPosition, MenuItemsCellColPositions[item], MenuItemLabels[item]);
            }
            RedrawCells();
        }