private void RefreshBoard() { Cursor.Current = Cursors.WaitCursor; try { UndoRedoManager.Instance.Clear(); SudokuSolutionNode selected_node = solutionsTree.SelectedSolutionNode; SudokuSolution selected_sol = solutionsCheckedListBox.SelectedSolution; foreach (TreeNode node in solutionsTree.Nodes) { SudokuSolutionNode sol_node = solutionsTree.TreeNodeToSolutionNode(node); if (sol_node.State == SudokuSolutionNodeState.Solution) { sol_node.Parent.RemoveNodes(sol_node); } } SudokuSolutionNode last = solutionsTree.TreeNodeToSolutionNode(solutionsTree.Nodes.Cast <TreeNode>().Last()); last.RemoveNodes(); SudokuSolutionNode root = SudokuSolutionNode.CreateTree(solutionsTree.SelectedSolutionNode.Root); solutionsTree.UpdateTree(root, solutionsTree.SelectedSolutionNode); } finally { Cursor.Current = Cursors.Default; } }
public async Task Setup() { context = await TestDatabase.GetDatabaseContext(); sut = new SolutionsRepository <SudokuSolution>(context); newSolution = new SudokuSolution(); }
public async Task <IRepositoryResponse> GetById(int id, bool fullRecord = true) { var result = new RepositoryResponse(); if (id == 0) { result.Success = false; return(result); } try { var query = new SudokuSolution(); if (fullRecord) { query = await context .SudokuSolutions .Include(s => s.Game) .ThenInclude(g => g.SudokuMatrix) .ThenInclude(m => m.SudokuCells) .Include(s => s.Game) .ThenInclude(g => g.SudokuMatrix) .ThenInclude(m => m.Difficulty) .FirstOrDefaultAsync(s => s.Id == id); } else { query = await context .SudokuSolutions .FirstOrDefaultAsync(s => s.Id == id); } if (query == null) { result.Success = false; return(result); } result.Success = true; result.Object = query; return(result); } catch (Exception exp) { result.Success = false; result.Exception = exp; return(result); } }
public ActionResult <SudokuSolution> GetSolution(SudokuSolutionRequest solutionRequest) { if (_service.IsSolutionRequestValid(solutionRequest)) { SudokuSolution solution = _service.FindSolution(solutionRequest); return(solution); } return(BadRequest()); }
public void FindSolution_NoSolutionFound_ReturnsFalse() { // Arrange SudokuSolutionRequest request = new SudokuSolutionRequest() { currentBoard = GetInvalidFormattedBoard() }; // Act SudokuSolution solution = _service.FindSolution(request); // Assert Assert.IsFalse(solution.isSuccessful, "Should return false"); }
public override void Redo() { base.Redo(); SudokuSolution sol = null; if (m_list.SelectedSolutionNode != null) { sol = m_list.SelectedSolutionNode.Solution.Rotate(m_list.SelectedSolutionNode.Board); } m_tree.InitTree(new SudokuBoard(m_tree.SelectedSolutionNode.Board).Rotate()); if (sol != null) { m_list.SelectedItem = m_list.Items.Cast <SudokuSolution>().FirstOrDefault(s => EqualsWithoutStates(sol, s)); } }
public void Solve(SudokuSolution a_solution = null) { if (a_solution == null) { a_solution = SelectedSolutionNode.Nodes.First().Solution; } SudokuSolutionNode solution_node = TreeNodeToSolutionNode(SelectedNode); solution_node = solution_node.Nodes.FirstOrDefault(n => Object.ReferenceEquals(n.Solution, a_solution)); if (solution_node != null) { solution_node.Parent.RemoveNodes(solution_node); } solution_node.Solve(); UpdateTree(solution_node.Root); }
private bool EqualsWithoutStates(SudokuSolution a_solution1, SudokuSolution a_solution2) { if (a_solution1.Type != a_solution2.Type) { return(false); } if (!a_solution1.Removed.Exact(a_solution2.Removed, Comparators.SudokuNumberRowColComparer.Instance)) { return(false); } if (!a_solution1.Stayed.Exact(a_solution2.Stayed, Comparators.SudokuNumberRowColComparer.Instance)) { return(false); } if (!a_solution1.Solved.Exact(a_solution2.Solved, Comparators.SudokuNumberRowColComparer.Instance)) { return(false); } return(a_solution1.ColorUnits.Equals(a_solution2.ColorUnits)); }
public async Task <ISolutionResult> Solve( ISolutionRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var result = new SolutionResult(); try { var solvedSolutions = ((await solutionsRepository.GetSolvedSolutions()).Objects) .ConvertAll(s => (SudokuSolution)s); var intList = new List <int>(); intList.AddRange(request.FirstRow); intList.AddRange(request.SecondRow); intList.AddRange(request.ThirdRow); intList.AddRange(request.FourthRow); intList.AddRange(request.FifthRow); intList.AddRange(request.SixthRow); intList.AddRange(request.SeventhRow); intList.AddRange(request.EighthRow); intList.AddRange(request.NinthRow); var sudokuSolver = new SudokuMatrix(intList); await sudokuSolver.Solve(); if (sudokuSolver.IsValid()) { var solution = new SudokuSolution(sudokuSolver.ToIntList()); var addResultToDataContext = true; if (solvedSolutions.Count > 0) { foreach (var solvedSolution in solvedSolutions) { if (solvedSolution.ToString().Equals(solution.ToString())) { addResultToDataContext = false; } } } if (addResultToDataContext) { solution = (SudokuSolution)(await solutionsRepository.Create(solution)).Object; } else { solution = solvedSolutions.Where(s => s.SolutionList.IsThisListEqual(solution.SolutionList)).FirstOrDefault(); } result.Success = true; result.Solution = solution; result.Message = SolutionsMessages.SudokuSolutionFoundMessage; } else { intList = sudokuSolver.ToIntList(); if (solvedSolutions.Count > 0) { var solutonInDB = false; foreach (var solution in solvedSolutions) { var possibleSolution = true; for (var i = 0; i < intList.Count - 1; i++) { if (intList[i] != 0 && intList[i] != solution.SolutionList[i]) { possibleSolution = false; break; } } if (possibleSolution) { solutonInDB = possibleSolution; result.Success = possibleSolution; result.Solution = solution; result.Message = SolutionsMessages.SudokuSolutionFoundMessage; break; } } if (!solutonInDB) { result.Success = false; result.Solution = null; result.Message = SolutionsMessages.SudokuSolutionNotFoundMessage; } } else { result.Success = false; result.Solution = null; result.Message = SolutionsMessages.SudokuSolutionNotFoundMessage; } } return(result); } catch (Exception exp) { result.Success = false; result.Message = exp.Message; return(result); } }
private SudokuSolution DFSSudoku(int[,] boardx, RemainingOptions[,] possibilities, int row, int col) { //int[,] newboardx = (int[,])boardx.Clone(); SudokuSolution result = new SudokuSolution(); while (boardx[row, col] != 0) { if (col < 8) { col++; } else { //col=8 if (row < 8) { col = 0; row++; } } if ((col == 8) && (row == 8)) { break; } } //Last spot? if ((row == 8) && (col == 8)) { int[,] newboardx = new int[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { newboardx[i, j] = boardx[i, j]; } } //wrapping up solution if (possibilities[row, col].options.Count > 0) { newboardx[8, 8] = (int)possibilities[8, 8].options[0]; result.board = newboardx; result.Solved = true; } else { //no Answer for this path newboardx[8, 8] = -1; result.board = newboardx; result.Solved = false; } return(result); } int nextrow = 0, nextcol = 0; if (col < 8) { nextrow = row; nextcol = col + 1; } else { //col=8 if (row < 8) { nextcol = 0; nextrow = row + 1; } } if (possibilities[row, col].options.Count > 1) { foreach (int x in possibilities[row, col].options) { int[,] newboardx = new int[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { newboardx[i, j] = boardx[i, j]; } } newboardx[row, col] = x; //clone/copy the possibilities - except the current one RemainingOptions[,] newpossibilities = CloneOptions(possibilities); //for [row, col] newpossibilities[row, col] = new RemainingOptions(); ArrayList tempList = new ArrayList(); tempList.Add(x); newpossibilities[row, col].options = tempList; //update possibilities - Clean Up here UpdateOptions(newpossibilities, x, row, col); //Recursive Call forward from here result = DFSSudoku(newboardx, newpossibilities, nextrow, nextcol); if (result.Solved == true) { //result.board = newboardx; return(result); } } //should not reach here??? //result.board = newboardx; return(result); } else { //possibilities[row, col].options.Count == 1 or == 0 //clone/copy the possiblities - except the current one //update possbilities //if col<8, col++ //if col==8 && row<8, col=0, row++ if (possibilities[row, col].options.Count == 1) { int[,] newboardx = new int[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { newboardx[i, j] = boardx[i, j]; } } int val = (int)possibilities[row, col].options[0]; newboardx[row, col] = val; //clone/copy the possibilities - except the current one RemainingOptions[,] newpossibilities = CloneOptions(possibilities); //for [row, col] newpossibilities[row, col] = new RemainingOptions(); ArrayList tempList = new ArrayList(); tempList.Add(val); newpossibilities[row, col].options = tempList; //update possibilities - Clean Up here UpdateOptions(newpossibilities, val, row, col); //Recursive Call forward from here return(DFSSudoku(newboardx, newpossibilities, nextrow, nextcol)); } else //Count==0 { //result.board= newboardx; result.board[row, col] = -1; result.Solved = false; return(result); } } }
public void SolveSudoku(char[,] board) { int[,] board2 = new int[9, 9]; RemainingOptions[,] theoptions = new RemainingOptions[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i, j] == '.') { theoptions[i, j] = new RemainingOptions(0); board2[i, j] = 0; } else { board2[i, j] = (int)(board[i, j] - '0'); theoptions[i, j] = new RemainingOptions(board2[i, j]); } } } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int temp = board2[i, j]; //do following only if [i,j] not empty if (temp != 0) { for (int k = 0; k < 9; k++) { //process the rows if (k != j) { theoptions[i, k].RemoveOption(temp); } //process the columns if (k != i) { theoptions[k, j].RemoveOption(temp); } } //process the cell int i0 = (int)(i / 3) * 3; int i1 = i % 3; int j0 = (int)(j / 3) * 3; int j1 = j % 3; for (int m = 0; m < 3; m++) { for (int n = 0; n < 3; n++) { if ((m != i1) || (n != j1)) { theoptions[i0 + m, j0 + n].RemoveOption(temp); } } } } } } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { Console.Write("{0}", board[i, j]); } Console.WriteLine(""); } SudokuSolution answer = DFSSudoku(board2, theoptions, 0, 0); if (answer.Solved == true) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i, j] == '.') { board[i, j] = (char)('0' + answer.board[i, j]); } } Console.WriteLine(""); } } }
/// <summary> /// This method runs the game /// </summary> /// <param name="savedGames">Intakes the List of SudokuConsoleGames</param> public void Play(ref List <SudokuConsoleGame> savedGames) { #region Play Fields // Determines if the user keeps playing bool _continue = true; // This field stores the user's command string _command; #endregion // Instantiate a screen instance DisplayScreens screen = new DisplayScreens(); // Instantiate a game stopwatch, this is used to calculate the score Stopwatch gameStopWatch = new Stopwatch(); // Start the stopwatch gameStopWatch.Start(); #region The Game Loop // The game loop do { // Load the game screen screen.GameScreen(ElementList, ElementSB); // Intake the users command _command = Console.ReadLine(); // Convert user command to uppercase so its case insensitive _command = _command.ToUpper(); // Remove starting and trailing empty spaces _command = _command.Trim(); #region Enter or Delete Command // These commands allow the user to enter and delete a value // The code to select the x and y coordinate is the same for each value // The initial choice from the user determines if this is an update or delete if (_command.Equals("1") || _command.Equals("ENTER") || _command.Equals("2") || _command.Equals("DELETE")) // If user command equals 1 or ENTER { // bool to test if the x coordinate is valid bool _continueX = true; do { Console.Write("\n\tEnter the X Coordinate> "); string _xValue = Console.ReadLine(); if (_xValue.TryParse()) { int _xInt = Convert.ToInt32(_xValue); if (_xInt > 0 && _xInt < 10) { bool _continueY = true; do { Console.Write("\n\tEnter the Y Coordinate> "); string _yValue = Console.ReadLine(); if (_yValue.TryParse()) { int _yInt = Convert.ToInt32(_yValue); if (_yInt > 0 && _yInt < 10) { // The indexer to change the string int indexer; // The indexer to access the element from the element string int indexer2; // The x value will be transformed to a int a = 0; // The y value will be transformed to b int b = 0; // The b2 value is required to index the element int b2 = 0; // Transform x into a for (int i = 1; i < _xInt; i++) { a = a + 2; } // Transform y int b for (int i = 1; i < _yInt; i++) { b = b + 18; } // Transform y int b2 for (int i = 1; i < _yInt; i++) { b2 = b2 + 9; } // Add a and b to ascertain the indexer indexer = a + b; // Add _xInt and b2 to ascertain indexer2 indexer2 = _xInt + b2 - 1; if (ElementList[indexer2].DisplayHint == false) { bool _userEntryInvalid = true; do { if (_command.Equals("1") || _command.Equals("ENTER")) { Console.Write("\n\tEnter a number from 1 through 9> "); string _userEntry = Console.ReadLine(); if (_userEntry.TryParse()) { int _userInt = Convert.ToInt32(_userEntry); if (_userInt > 0 && _userInt < 10) { ElementSB.Remove(indexer, 1); ElementSB.Insert(indexer, _userEntry); Console.Clear(); _continueX = false; _continueY = false; _userEntryInvalid = false; } else { InvalidCoordinate(); } } else { InvalidCoordinate(); } } else { ElementSB.Remove(indexer, 1); ElementSB.Insert(indexer, "_"); Console.Clear(); _continueX = false; _continueY = false; _userEntryInvalid = false; } }while (_userEntryInvalid); } else { Console.WriteLine("\n\tThis value is a hint provided by the system and cannot be changed."); Console.WriteLine("\tPlease try again.\n\n\t\t (Press Enter to Continue)"); Console.ReadLine(); break; } } else { InvalidCoordinate(); } } }while (_continueY == true); } else { InvalidCoordinate(); } } else { InvalidCommand(); } }while (_continueX == true); } #endregion #region Reset Command // This command allows the user to reset the board else if (_command.Equals("3") || _command.Equals("RESET")) // If user command equals 3 or RESET { ClearSolution(ElementSB, ElementList); Console.Clear(); } #endregion #region Check Command // This command allows the user to check his answer else if (_command.Equals("4") || _command.Equals("CHECK")) // If user command equals 4 or CHECK { // Stop the gameStopWatch gameStopWatch.Stop(); // Save the elapsed seconds to ticks Ticks = Ticks + gameStopWatch.Elapsed.Seconds; // Reset the gameStopWatch gameStopWatch.Reset(); // Determine if the user wins! if (SolutionString.Equals(ElementSB.ToString())) { // Calculate the score Score = CalculateSolution(); // Save the score if (savedGames.Contains(this)) { // If the game was previously in the list, remove the old reference savedGames.Remove(this); } // Add the game to the list and sort by DateCreated property savedGames.Add(this); //savedGames.Sort(); // Create the saved game repository SavedGameRepository savedGameRepository = new SavedGameRepository(); // Set the saved game repository list equal to savedGames savedGameRepository.SavedGames = savedGames; // Save the game Serializer serialize = new Serializer(); serialize.SerializeRepository("SavedGames.dat", savedGameRepository); Console.Clear(); screen.VictoryScreen(this); _continue = false; } else { // If the difficulty level is easy or medium the game provides hints if (GameDifficulty == Difficulty.EASY || GameDifficulty == Difficulty.MEDIUM) { // If the solution is not correct the keeps the correct responses from the user Console.WriteLine("\n\tClose but no cigar!\n\n\t\t (Press Enter to Continue)"); Console.ReadLine(); Console.WriteLine("\tHere, I'll help you out and show you were you're right.\n\n\t\t (Press Enter to Continue)"); Console.ReadLine(); if (GameDifficulty == Difficulty.EASY) { // Turns the claimant's solution to a string string _assistanceString = ElementSB.ToString(); // Turns the solution to a char array char[] _solutionArray = SolutionString.ToCharArray(); // Turns the user's solution to a char array char[] _assistanceArray = _assistanceString.ToCharArray(); // If the value in the user's char array is incorrect its converted to "_" for (int i = 0; i < _assistanceString.Length; i++) { if (_solutionArray[i] != _assistanceArray[i]) { _assistanceArray[i] = '_'; } } // Clears the user's response ElementSB.Clear(); // Refills the element string builder with the corrected array foreach (char a in _assistanceArray) { ElementSB.Append(a); } // Add 100 Demerits Demerits = Demerits + 200; Console.Clear(); } else if (GameDifficulty == Difficulty.MEDIUM) { int _correctAnswers = 0; for (int i = 0; i < SudokuSolution.Count; i++) { int j = i * 2; if (ElementSB.ToString().TryParse()) { if (Convert.ToInt32(ElementSB.ToString().ElementAt(j)) == SudokuSolution.ElementAt(i)) { ++_correctAnswers; } } } Console.WriteLine("\n\t{0} of your answers are correct.\n\n\tPlease try again.\n\n\t\t (Press Enter to Continue"); // Add 10 Demerits Demerits = Demerits + 100; Console.Clear(); } } // If the difficulty level is hard the game does not provide hints else if (GameDifficulty == Difficulty.HARD) { Console.WriteLine("\n\tClose but no cigar!\n\tTry again!\n\n\t\t (Press Enter to Continue)"); Console.ReadLine(); Console.Clear(); } // Restart the gameStopWatch gameStopWatch.Start(); } } #endregion #region Save Command // This command allows the user to save the game else if (_command.Equals("5") || _command.Equals("SAVE")) // If user command equals 5 or SAVE { // Stop the gameStopWatch gameStopWatch.Stop(); // Save the elapsed seconds to ticks Ticks = Ticks + gameStopWatch.Elapsed.Seconds; // Reset the gameStopWatch gameStopWatch.Reset(); if (savedGames.Contains(this)) { // If the game was previously in the list, remove the old reference savedGames.Remove(this); } // Add the game to the list and sort by DateCreated property savedGames.Add(this); //savedGames.Sort(); // Create the saved game repository SavedGameRepository savedGameRepository = new SavedGameRepository(); // Set the saved game repository list equal to savedGames savedGameRepository.SavedGames = savedGames; // Save the game Serializer serialize = new Serializer(); serialize.SerializeRepository("SavedGames.dat", savedGameRepository); Console.WriteLine("\n\tYour game has been saved.\n\n\t\t (Press Enter to Continue)"); Console.ReadLine(); Console.Clear(); // Restart the gameStopWatch gameStopWatch.Start(); } #endregion #region Exit Command // This command allows the user to return to the main menu else if (_command.Equals("6") || _command.Equals("EXIT")) // If user command equals 6 of EXIT { string exitGame = string.Empty; Console.Write("\n\tPlease note that unsaved changes will be lost.\n\n\tDo you wish to return to the main menu?\n\n\tYes/No> "); exitGame = Console.ReadLine(); // Ensure response is not case sensitive exitGame = exitGame.ToUpper(); // Remove starting and trailing empty spaces exitGame = exitGame.Trim(); if (exitGame.Equals("YES") || exitGame.Equals("Y")) { Console.WriteLine("\n\tReturning to main menu.\n\n\t\t (Press Enter to Return to Main Menu)"); Console.ReadLine(); _continue = false; } else { Console.Clear(); } } #endregion else { // If the user fails to enter a valid command Console.WriteLine("\n\tPlease enter a valid command.\n\n\t\t (Press Enter to Continue)"); Console.ReadLine(); Console.Clear(); } }while (_continue == true); #endregion }