public void UndoMove_With_Not_Executed_Move_Should_Not_Alter_PuzzleState() { SudokuPuzzle sudokuPuzzle = new SudokuGenerator().Generate(); SudokuMove sudokuMove = new SudokuMove(1, 1, 9); Assert.IsFalse(sudokuPuzzle.ExecuteMove(sudokuMove)); }
public ActionResult SolveSudoku(string sudokuToProcess) { var stopWatch = Stopwatch.StartNew(); SortedList <string, string> extendedGridValues = SudokuGenerator.PopulateGridWithPossibleValues(sudokuToProcess); SortedList <string, string> oneDimensionalSudokuResult = SudokuGenerator.Search(extendedGridValues); string[,] SudokuArrayOutput = null; if (oneDimensionalSudokuResult != null && oneDimensionalSudokuResult.Count > 0) { SudokuArrayOutput = new string[9, 9]; int elementPosition = 0; for (int row = 0; row < 9; row++) { for (int cell = 0; cell < 9; cell++) { SudokuArrayOutput[row, cell] = oneDimensionalSudokuResult.Values.ToArray()[elementPosition]; elementPosition++; } } } stopWatch.Stop(); var returnObject = new { timeTakenToProcess = Convert.ToInt32(stopWatch.Elapsed.TotalMilliseconds), sudokuOutput = SudokuArrayOutput }; return(Json(returnObject)); }
public void TestAddNumbers() { SudokuPuzzle sudoku = SudokuGenerator.AddNumbers(SudokuPuzzleTest.Size, SudokuPuzzleTest.Difficulty); Assert.ThrowsException <ArgumentNullException>(() => SudokuGenerator.AddNumbers(null)); Assert.ThrowsException <ArgumentException>(() => SudokuGenerator.AddNumbers(SudokuPuzzle.MaximumSupportedSize, SudokuDifficulty.None)); if (SudokuPuzzle.MaximumSupportedSize > 1) { Assert.ThrowsException <ArgumentException>(() => SudokuGenerator.AddNumbers(2, SudokuDifficulty.Easy)); } Assert.ThrowsException <ArgumentOutOfRangeException>(() => SudokuGenerator.AddNumbers(SudokuPuzzle.MaximumSupportedSize + 1, SudokuDifficulty.Easy)); Assert.ThrowsException <ArgumentOutOfRangeException>(() => SudokuGenerator.AddNumbers(-1, SudokuDifficulty.Easy)); for (int i = 0; i < sudoku.Size; i++) { for (int j = 0; j < sudoku.Size; j++) { int number = sudoku[i, j]; Assert.IsFalse(sudoku.RowContains(i, j, number, true)); Assert.IsFalse(sudoku.ColumnContains(i, j, number, true)); Assert.IsFalse(sudoku.BlockContains(i, j, number, true)); } } }
public void Puzzle_Of_Type_SudokuPuzzle_Property_Name_Should_Return_SudokuPuzzle() { const string expected = "SudokuPuzzle"; Puzzle sudokuPuzzle = new SudokuGenerator().Generate(); Assert.AreEqual(expected, sudokuPuzzle.Name); }
public void Validate_Sudoku_Input_String() { var sudoku = "85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4."; bool actual = SudokuGenerator.IsInputSudokuValid(sudoku); Assert.IsTrue(actual, "Valid sudoku - Length and allowed degits/characters [0-9.]"); }
private static int Generate(int size, SudokuDifficulty difficulty, String outfile) { SudokuPuzzle sudoku = SudokuGenerator.Generate(size, difficulty); if (outfile is null) { Console.WriteLine(sudoku); } else { if (Program.WriteToFile(sudoku.ToString(), outfile)) { Console.WriteLine($"Generated sudoku written to {outfile}"); } else { Console.WriteLine(Program.FileOutputErrorMessage); return(Program.FileOutputError); } } return(0); }
public void When_Invalid_Sudoku_Do_Not_Populate_Grid_With_Possible_Values() { var invalidSudoku = "A5...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4."; SortedList <string, string> sortedList = SudokuGenerator.PopulateGridWithPossibleValues(invalidSudoku); Assert.AreEqual(0, sortedList == null ? 0 : 1, "Invalid sudoku."); }
public void Should_return_completed_board_when_difficulty_is_none() { var board = SudokuGenerator.NewSudoku(SudokuDifficulty.None); Assert.That(board.EmptyCells.Count(), Is.EqualTo(0)); Assert.That(board.IsCompleted, Is.True); }
private void OnSingleButtonFragmentClick(Object sender, EventArgs e) { SingleButtonFragment singleButtonFragment = this.FragmentManager.FindFragmentByTag("button_fragment") as SingleButtonFragment; SudokuView sudokuView = this.View.FindViewById <SudokuView>(Resource.Id.sudoku_view); String addText = this.Resources.GetString(Resource.String.add_button_text); String removeText = this.Resources.GetString(Resource.String.remove_button_text); String playText = this.Resources.GetString(Resource.String.play_button_text); if (singleButtonFragment.Text == addText) { SudokuGenerator.AddNumbers(this.ViewModel.Sudoku); sudokuView.Update(); this.ViewModel.ButtonText = singleButtonFragment.Text = removeText; } else if (singleButtonFragment.Text == removeText) { SudokuGenerator.RemoveNumbers(this.ViewModel.Sudoku); sudokuView.Update(); this.ViewModel.ButtonText = singleButtonFragment.Text = playText; } else if (singleButtonFragment.Text == playText) { this.Stop(); FragmentTransaction ft = this.FragmentManager.BeginTransaction(); ft.Remove(singleButtonFragment); ft.Commit(); this.Activity.Intent.PutExtra("action", (int)ActionType.Play); this.Activity.Intent.Extras.PutInt("action", (int)ActionType.Play); ActionType action = (ActionType)this.Activity.Intent.Extras.GetInt("action", (int)ActionType.None); this.ViewModel.ButtonText = null; this.Start(); } }
public void TestGetIncorrect() { SudokuGenerator.AddNumbers(this.Sudoku); Random random = new Random(); for (int i = 0; i < SudokuPuzzle.MaximumSupportedSize * 2; i++) { int row = random.Next(this.Sudoku.Size), column = random.Next(this.Sudoku.Size); int number; do { number = random.Next(0, this.Sudoku.Size + 1); } while (this.Sudoku[row, column] == number); } IEnumerable <Tuple <int, int> > incorrect = this.Sudoku.GetIncorrect(); for (int i = 0; i < this.Sudoku.Size; i++) { for (int j = 0; j < this.Sudoku.Size; j++) { if (!this.Sudoku.IsCorrect(i, j)) { Assert.IsTrue(incorrect.Contains(new Tuple <int, int>(i, j))); } } } }
public void TestEquals() { SudokuDifficulty newDifficulty = SudokuPuzzleTest.Difficulty == SudokuDifficulty.None ? SudokuDifficulty.Easy : SudokuDifficulty.None; SudokuPuzzle puzzle = new SudokuPuzzle(this.Sudoku.Size, newDifficulty); SudokuGenerator.AddNumbers(puzzle); for (int i = 0; i < this.Sudoku.Size; i++) { for (int j = 0; j < this.Sudoku.Size; j++) { this.Sudoku[i, j] = puzzle[i, j]; } } Assert.AreEqual(this.Sudoku, puzzle); Assert.IsTrue(this.Sudoku.Equals(puzzle)); Assert.IsTrue(this.Sudoku == puzzle); Assert.IsFalse(this.Sudoku != puzzle); Assert.IsFalse(this.Sudoku == null); Assert.IsFalse(null == this.Sudoku); SudokuPuzzle nullPuzzle = null; Assert.IsTrue(null == nullPuzzle); this.Sudoku[0, 0] = 0; Assert.AreNotEqual(this.Sudoku, puzzle); }
public static void Initialize(TestContext testContext) { PuzzleGenerator <SudokuPuzzle> sudokuGenerator = new SudokuGenerator(); PuzzlePrinter <SudokuPuzzle> sudokuPrinter = new SudokuPrinter(); _sudokuPuzzleService = new SudokuPuzzleService(sudokuGenerator, sudokuPrinter); }
public bool SetCellValue(int value, int row, int column) { if (SudokuGenerator.SetValue(value, row, column)) { return(true); } return(false); }
public GameVM(GameDifficulty difficulty) { this.difficulty = difficulty; Board = new Board(); Timer = new GameTimer(); Generator = new SudokuGenerator(Board, difficulty); Manager = new SudokuManager(Board, Generator.SolvedSudokuValues); }
public void SudokuPuzzle_Description_Equals_Expected() { const string expected = "A puzzle in which missing numbers are to be filled into a 9 by 9 grid " + "of squares which are subdivided into 3 by 3 boxes so that every row, every column, " + "and every box contains the numbers 1 through 9."; Puzzle sudokuPuzzle = new SudokuGenerator().Generate(); Assert.AreEqual(expected, sudokuPuzzle.Description); }
public ActionResult Generate() { var sudoku = new SudokuModel(); var generator = new SudokuGenerator(); sudoku.board = generator.board; return(View(sudoku)); }
static void testSudokuGenerator() { SudokuGenerator sudokuGenerator0 = new SudokuGenerator(1, Level.All); sudokuGenerator0.Execute(); SudokuGenerator sudokuGenerator1 = new SudokuGenerator(2); sudokuGenerator1.ExecuteAll(); }
public void GeneratorTest() { var grid = SudokuGenerator.GenerateGrid(GameType.Sudoku); var solvedGrid = SudokuSolver.Solve(grid); solvedGrid.Solvable.ShouldBe(true); solvedGrid.Unique.ShouldBe(true); SudokuSolver.IsSolved(solvedGrid.SolvedGrid).ShouldBe(true); }
public void Solve_On_A_Solved_SudokuPuzzle_Should_Return_True() { SudokuPuzzle sudokuPuzzle = new SudokuGenerator().Generate(); using (SudokuSolver sudokuSolver = new SudokuSolver(sudokuPuzzle)) { sudokuSolver.Solve(); Assert.IsTrue(sudokuSolver.Solve()); } }
public void TestRemoveNumbers() { Assert.ThrowsException <ArgumentNullException>(() => SudokuGenerator.RemoveNumbers(null)); SudokuPuzzle sudoku = SudokuGenerator.AddNumbers(SudokuPuzzleTest.Size, SudokuPuzzleTest.Difficulty); Console.WriteLine(sudoku); SudokuPuzzle original = (SudokuPuzzle)sudoku.Clone(); SudokuGenerator.RemoveNumbers(sudoku); Console.WriteLine(sudoku); SudokuSolver.RecursiveSolve(sudoku); Assert.AreEqual(original, sudoku); }
public ActionResult <SudokuPuzzleDTO> Generate(SudokuDifficulty difficulty, int?seed) { ISudokuGenerator generator = new SudokuGenerator(); ISudokuPuzzle puzzle = generator.Generate(difficulty, seed); SudokuPuzzleDTO puzzleDTO = new SudokuPuzzleDTO() { Puzzle = puzzle.ToString(), Seed = puzzle.Id }; return(puzzleDTO); }
private void CreateSeedFile() { //Creates 4 seeds of each difficulty //Should only be used to create the base data, and not to add new seeds List <Sudoku> seeds_ = new List <Sudoku>(); foreach (Sudoku sudoku in sudokus_) { seeds_.Add(SudokuGenerator.GenerateSeed(sudoku)); } SaveLoad.SaveSeeds(seeds_); }
public void TestInitializer() { WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(); PuzzleGenerator <SudokuPuzzle> sudokuGenerator = new SudokuGenerator(); PuzzlePrinter <SudokuPuzzle> sudokuPrinter = new SudokuPrinter(); IPuzzleService <SudokuPuzzle> sudokuPuzzleService = new SudokuPuzzleService(sudokuGenerator, sudokuPrinter); _httpHandler = new HttpClientHandlerMock(); IRestServiceConnector restServiceConnector = new RestServiceConnector(_httpHandler); IPuzzleStorageService puzzleStorageService = new PuzzleStorageService(restServiceConnector); _puzzleHandler = new PuzzleHandler(webSocketConnectionManager, sudokuPuzzleService, puzzleStorageService); }
internal static int Main(String[] args) { if (!Console.IsInputRedirected) { Console.Title = "Sudoku"; } if (args.Length == 0) { if (Console.IsInputRedirected || Console.IsOutputRedirected) { Console.WriteLine(Program.IOErrorMessage); return(Program.IOError); } Window window = new Window(SudokuGenerator.Generate(Program.DefaultSize, Program.DefaultDifficulty)); window.Init(); return(0); } if (!Program.ParseArguments(args, out int command, out int size, out SudokuDifficulty difficulty, out String filename, out String outfile)) { Console.WriteLine(Program.UsageMessage); return(Program.UsageMessageWarning); } switch (command) { case Program.CompareCommand: return(Program.Compare(filename, outfile)); case Program.EnumerateCommand: return(Program.Enumerate(filename)); case Program.GenerateCommand: return(Program.Generate(size, difficulty, outfile)); case Program.InteractiveCommand: return(Program.Interactive(size, filename)); case Program.PrintCommand: return(Program.Print(filename)); case Program.SolveCommand: return(Program.Solve(filename, outfile)); default: Console.WriteLine(Program.UsageMessage); return(Program.UsageMessageWarning); } }
public void TestSudokuGenerator() { try { #region samurai level { var generator = SudokuGenerator.GetGenerator(9, Common.Difficulty.Samurai); var unsolvedBoard = generator.Generate(); Assert.IsNotNull(unsolvedBoard); var solvedBoard = SudokuSolver.GetSolver(unsolvedBoard).Solve(); Assert.AreEqual(generator.BaseBoard, solvedBoard); } #endregion #region hard level { var generator = SudokuGenerator.GetGenerator(9, Common.Difficulty.Hard); var unsolvedBoard = generator.Generate(); Assert.IsNotNull(unsolvedBoard); var solvedBoard = SudokuSolver.GetSolver(unsolvedBoard).Solve(); Assert.AreEqual(generator.BaseBoard, solvedBoard); } #endregion #region medium level { var generator = SudokuGenerator.GetGenerator(9, Common.Difficulty.Medium); var unsolvedBoard = generator.Generate(); Assert.IsNotNull(unsolvedBoard); var solvedBoard = SudokuSolver.GetSolver(unsolvedBoard).Solve(); Assert.AreEqual(generator.BaseBoard, solvedBoard); } #endregion #region easy level { var generator = SudokuGenerator.GetGenerator(9, Common.Difficulty.Easy); var unsolvedBoard = generator.Generate(); Assert.IsNotNull(unsolvedBoard); var solvedBoard = SudokuSolver.GetSolver(unsolvedBoard).Solve(); Assert.AreEqual(generator.BaseBoard, solvedBoard); } #endregion } catch (Exception ex) { Assert.Fail(ex.Message); } }
/// <summary> /// Run generation with ability to cancel /// </summary> private async Task Generate() { using (var generationTokenSource = new CancellationTokenSource()) { var generationSettings = new GenerationSettings { Difficulty = _model.SudokuDifficulty, Symmetry = _model.SudokuSymmetry, DifficultyPoints = _model.DifficultyPoints }; var generationTask = Task.Run(() => { _model.CurrentSudoku = SudokuGenerator.Generate(generationSettings, generationTokenSource.Token); }, generationTokenSource.Token); while (true) { using (var delayToken = CancellationTokenSource.CreateLinkedTokenSource(generationTokenSource.Token)) { var delayTask = Task.Delay(5_000, delayToken.Token); var finishedTask = await Task.WhenAny(generationTask, delayTask); if (finishedTask != generationTask) { if (AskToWait()) { continue; } generationTokenSource.Cancel(); await generationTask.ContinueWith(task => Console.WriteLine(@"Generation task cancelled"), TaskContinuationOptions.OnlyOnCanceled); break; } delayToken.Cancel(); await delayTask.ContinueWith(task => Console.WriteLine(@"Delay task cancelled"), TaskContinuationOptions.OnlyOnCanceled); break; } } } }
public void TestOperators() { SudokuGenerator.AddNumbers(this.Sudoku); SudokuPuzzle clone = (SudokuPuzzle)this.Sudoku.Clone(); Assert.AreEqual(this.Sudoku, clone); Assert.IsTrue(this.Sudoku.Equals(clone)); Assert.IsTrue(this.Sudoku == clone); int row = 0, column = 0; clone[row, column] = 0; Assert.AreNotEqual(this.Sudoku, clone); Assert.IsFalse(this.Sudoku.Equals(clone)); Assert.IsFalse(this.Sudoku == clone); Assert.IsTrue(this.Sudoku != clone); }
public void When_Invalid_Sudoku_Search_To_Fail() { var sudokuWithInvalidPositions = "44....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......"; bool actual = SudokuGenerator.IsInputSudokuValid(sudokuWithInvalidPositions); Assert.IsTrue(actual, "Valid length, degits in sudoku"); //Populate list will be called once var sortedList = SudokuGenerator.PopulateGridWithPossibleValues(sudokuWithInvalidPositions); Assert.AreEqual(1, sortedList == null ? 0 : 1, "Populating grid with possible values successfull"); //Search will be called and will retun null as result sortedList = SudokuGenerator.Search(sortedList); Assert.AreEqual(0, sortedList == null ? 0 : 1, "Search fails as only choice fails for the second degit and retuns null as output"); }
/** * Generates random puzzle with unique solution. * * @see SudokuGenerator * @see SudokuGenerator#PARAM_GEN_RND_BOARD * @see SudokuGenerator#generate() */ private void generateRandomPuzzle() { generator = new SudokuGenerator(SudokuGenerator.PARAM_GEN_RND_BOARD); setGeneratorOptions(); int[,] generated = generator.generate(); if (generator.getGeneratorState() == SudokuGenerator.GENERATOR_GEN_FINISHED) { trackPuzzleUndo(); puzzle = generated; } else { JanetConsole.println(">>> !!! Error while generating random puzzle !!! <<<"); JanetConsole.println(generator.getMessages()); } }
/** * Generates puzzle based on current puzzle * (different puzzle, same solution). * * @see SudokuGenerator * @see SudokuGenerator#PARAM_DO_NOT_TRANSFORM * @see SudokuGenerator#generate() */ private void generateFromCurrentPuzzle() { generator = new SudokuGenerator(puzzle, SudokuGenerator.PARAM_DO_NOT_TRANSFORM); setGeneratorOptions(); int[,] generated = generator.generate(); if (generator.getGeneratorState() == SudokuGenerator.GENERATOR_GEN_FINISHED) { trackPuzzleUndo(); puzzle = generated; } else { JanetConsole.println(">>> !!! Error while generating puzzle !!! <<<"); JanetConsole.println(generator.getMessages()); } }
/** * Test scenario implementation. * @param testId Test id. * @param threadId Thread id. * @return True is test successful, otherwise false. */ static bool runTest(int testId, int threadId) { bool testResult = true; String testDesc = "", resultDesc = ""; int[,] a = { {0,0,0,8,0,0,0,0,0}, {4,0,0,0,1,5,0,3,0}, {0,2,9,0,4,0,5,1,8}, {0,4,0,0,0,0,1,2,0}, {0,0,0,6,0,2,0,0,0}, {0,3,2,0,0,0,0,9,0}, {6,9,3,0,5,0,8,7,0}, {0,5,0,4,8,0,0,0,1}, {0,0,0,0,0,3,0,0,0} }; switch(testId) { case 0: testDesc = "SudokuSolver.setCell(int, int, int)"; { SudokuSolver s = new SudokuSolver(); s.setCell(0,0,0); s.setCell(1,0,4); s.setCell(2,0,0); s.setCell(3,0,0); s.setCell(4,0,0); s.setCell(5,0,0); s.setCell(6,0,6); s.setCell(7,0,0); s.setCell(8,0,0); s.setCell(0,1,0); s.setCell(1,1,0); s.setCell(2,1,2); s.setCell(3,1,4); s.setCell(4,1,0); s.setCell(5,1,3); s.setCell(6,1,9); s.setCell(7,1,5); s.setCell(8,1,0); s.setCell(0,2,0); s.setCell(1,2,0); s.setCell(2,2,9); s.setCell(3,2,0); s.setCell(4,2,0); s.setCell(5,2,2); s.setCell(6,2,3); s.setCell(7,2,0); s.setCell(8,2,0); s.setCell(0,3,8); s.setCell(1,3,0); s.setCell(2,3,0); s.setCell(3,3,0); s.setCell(4,3,6); s.setCell(5,3,0); s.setCell(6,3,0); s.setCell(7,3,4); s.setCell(8,3,0); s.setCell(0,4,0); s.setCell(1,4,1); s.setCell(2,4,4); s.setCell(3,4,0); s.setCell(4,4,0); s.setCell(5,4,0); s.setCell(6,4,5); s.setCell(7,4,8); s.setCell(8,4,0); s.setCell(0,5,0); s.setCell(1,5,5); s.setCell(2,5,0); s.setCell(3,5,0); s.setCell(4,5,2); s.setCell(5,5,0); s.setCell(6,5,0); s.setCell(7,5,0); s.setCell(8,5,3); s.setCell(0,6,0); s.setCell(1,6,0); s.setCell(2,6,5); s.setCell(3,6,1); s.setCell(4,6,0); s.setCell(5,6,0); s.setCell(6,6,8); s.setCell(7,6,0); s.setCell(8,6,0); s.setCell(0,7,0); s.setCell(1,7,3); s.setCell(2,7,1); s.setCell(3,7,2); s.setCell(4,7,0); s.setCell(5,7,9); s.setCell(6,7,7); s.setCell(7,7,0); s.setCell(8,7,0); s.setCell(0,8,0); s.setCell(1,8,0); s.setCell(2,8,8); s.setCell(3,8,0); s.setCell(4,8,0); s.setCell(5,8,0); s.setCell(6,8,0); s.setCell(7,8,1); s.setCell(8,8,0); int[,] b = s.getBoard(); if ( (SudokuStore.boardsAreEqual(a, b) == true) ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; testResult = false; SudokuStore.consolePrintln(s.getMessages()); } } break; case 1: testDesc = "SudokuSolver.getCellDigit(int, int)"; { SudokuSolver s1 = new SudokuSolver(a); SudokuSolver s2 = new SudokuSolver(); for (int i = 0; i < SudokuBoard.BOARD_SIZE; i++) for (int j = 0; j < SudokuBoard.BOARD_SIZE; j++) { int d = s1.getCellDigit(i, j); s2.setCell(i, j, d); } int[,] b = s2.getBoard(); if ( (SudokuStore.boardsAreEqual(a, b) == true) ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; testResult = false; } } break; case 2: testDesc = "SudokuSolver.getBoardCopy()"; { SudokuSolver s = new SudokuSolver(a); int[,] b = s.getBoard(); int[,] c = s.getBoardCopy(); if ( (SudokuStore.boardsAreEqual(b, c) == true) ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; testResult = false; } } break; case 3: testDesc = "SudokuSolver.getSolutionBoardCells()"; { SudokuSolver s = new SudokuSolver(a); s.solve(); int[,] b = s.getSolvedBoard(); int[,] c = SudokuStore.boardCopy(a); BoardCell[] sol = s.getSolutionBoardCells(); foreach (BoardCell bc in sol) c[bc.rowIndex, bc.colIndex] = bc.digit; if ( (SudokuStore.boardsAreEqual(b, c) == true) ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; testResult = false; } } break; case 4: testDesc = "SudokuSolver.getAllBoardCells()"; { SudokuSolver s = new SudokuSolver(a); int[,] b = s.getBoardCopy(); int[,] c = new int[SudokuBoard.BOARD_SIZE, SudokuBoard.BOARD_SIZE]; BoardCell[] bc = s.getAllBoardCells(); foreach (BoardCell cell in bc) { c[cell.rowIndex, cell.colIndex] = cell.digit; } if ( (SudokuStore.boardsAreEqual(b, c) == true) ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; testResult = false; } } break; case 5: testDesc = "SudokuSolver.getAllSolutionsList()"; { SudokuSolver s = new SudokuSolver( SudokuPuzzles.PUZZLE_NON_UNIQUE_SOLUTION ); s.findAllSolutions(); List<SudokuBoard> solList; solList = s.getAllSolutionsList(); foreach (SudokuBoard sb in solList) { if (SudokuStore.checkSolvedBoard( sb.board ) == false) { testResult = false; break; } } if ( testResult == true ) { resultDesc = "Expecting each solution valid - each is valid."; } else { resultDesc = "Expecting each solution valid - found not valid."; } } break; case 6: testDesc = "SudokuGenerator -> generate -> save -> load -> compare"; { String filePath = FileX.getTmpDir() + FileX.genRndFileName(20, "txt"); SudokuGenerator g = new SudokuGenerator(SudokuGenerator.PARAM_GEN_RND_BOARD); int[,] generated = g.generate(); g.saveBoard(filePath, "generated", "saved"); int[,] loaded = SudokuStore.loadBoard(filePath); FileX.removeFile(filePath); if (SudokuStore.boardsAreEqual(generated, loaded) == false) testResult = false; if ( testResult == true ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; } } break; case 7: testDesc = "SudokuSolver -> solve -> save -> load -> compare"; { String filePath = FileX.getTmpDir() + FileX.genRndFileName(20, "txt"); SudokuSolver s = new SudokuSolver(SudokuStore.getPuzzleExample()); s.solve(); int[,] solved = s.getSolvedBoard(); s.saveSolvedBoard(filePath, "solved", "saved"); int[,] loaded = SudokuStore.loadBoard(filePath); FileX.removeFile(filePath); if (SudokuStore.boardsAreEqual(solved, loaded) == false) testResult = false; if ( testResult == true ) { resultDesc = "Expecting equal - are equal."; } else { resultDesc = "Expecting equal - are not equal."; } } break; } if (testResult == true) SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + " " + testDesc + " " + resultDesc + " >>> ApiTests, result: OK"); else SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + " " + testDesc + " " + resultDesc + " >>> ApiTests, result: ERROR"); return testResult; }
/** * Test scenario implementation. * @param testId Test id. * @param threadId Thread id. * @return True is test successful, otherwise false. */ static bool runTest(int testId, int threadId) { SudokuSolver solverGen, solverInit; SudokuGenerator g; int solUnq; int[,] genPuzzle; int[,] solvedGen, solvedInit, initBoard; bool testResult = true; switch(testId) { case 0: for (int example = 0; example < SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES; example++) { g = new SudokuGenerator(example, SudokuGenerator.PARAM_DO_NOT_TRANSFORM); genPuzzle = g.generate(); solverGen = new SudokuSolver(genPuzzle); ErrorCodes.consolePrintlnIfError(solverGen.solve()); solverInit = new SudokuSolver(example); ErrorCodes.consolePrintlnIfError(solverInit.solve()); solUnq = solverGen.checkIfUniqueSolution(); ErrorCodes.consolePrintlnIfError(solUnq); solvedGen = solverGen.getSolvedBoard(); solvedInit = solverInit.getSolvedBoard(); if ( (solUnq == SudokuSolver.SOLUTION_UNIQUE) && ( SudokuStore.boardsAreEqual(solvedGen, solvedInit) == true ) ) { //SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example number, example: " + example + ", solution unique and correct: YES, time (g, s1, s2): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., " + solverInit.getComputingTime() + " s."); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example number, example: " + example + ", solution unique and correct: NO, time (g, s1, s2): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., " + solverInit.getComputingTime() + " s."); Console.WriteLine("Initial board"); SudokuStore.consolePrintBoard(SudokuStore.getPuzzleExample(example)); Console.WriteLine("Generated puzzle"); SudokuStore.consolePrintBoard(genPuzzle); Console.WriteLine("Solved initial board"); SudokuStore.consolePrintBoard(solvedInit); Console.WriteLine("Solved generated puzzle"); SudokuStore.consolePrintBoard(solvedGen); } } break; case 1: for (int example = 0; example < SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES; example++) { initBoard = SudokuStore.getPuzzleExample(example); g = new SudokuGenerator(initBoard, SudokuGenerator.PARAM_DO_NOT_TRANSFORM, SudokuGenerator.PARAM_DO_NOT_SOLVE); genPuzzle = g.generate(); solverGen = new SudokuSolver(genPuzzle); ErrorCodes.consolePrintlnIfError(solverGen.solve()); solverInit = new SudokuSolver(initBoard); ErrorCodes.consolePrintlnIfError(solverInit.solve()); solUnq = solverGen.checkIfUniqueSolution(); ErrorCodes.consolePrintlnIfError(solUnq); solvedGen = solverGen.getSolvedBoard(); solvedInit = solverInit.getSolvedBoard(); if ( (solUnq == SudokuSolver.SOLUTION_UNIQUE) && ( SudokuStore.boardsAreEqual(solvedGen, solvedInit) == true ) ) { //SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example board, example: " + example + ", solution unique and correct: YES, time (g, s1, s2): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., " + solverInit.getComputingTime() + " s."); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example board, example: " + example + ", solution unique and correct: NO, time (g, s1, s2): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., " + solverInit.getComputingTime() + " s."); Console.WriteLine("Initial board"); SudokuStore.consolePrintBoard(initBoard); Console.WriteLine("Generated puzzle"); SudokuStore.consolePrintBoard(genPuzzle); Console.WriteLine("Solved initial board"); SudokuStore.consolePrintBoard(solvedInit); Console.WriteLine("Solved generated puzzle"); SudokuStore.consolePrintBoard(solvedGen); } } break; case 2: for (int example = 0; example < SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES; example++) { g = new SudokuGenerator(example); genPuzzle = g.generate(); solverGen = new SudokuSolver(genPuzzle); ErrorCodes.consolePrintlnIfError(solverGen.solve()); solUnq = solverGen.checkIfUniqueSolution(); ErrorCodes.consolePrintlnIfError(solUnq); solvedGen = solverGen.getSolvedBoard(); if ( (solUnq == SudokuSolver.SOLUTION_UNIQUE) && ( SudokuStore.checkPuzzle(genPuzzle) == true ) ) { //SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example number, example: " + example + ", solution unique and correct: YES, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example number, example: " + example + ", solution unique and correct: NO, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); Console.WriteLine("Generated puzzle"); SudokuStore.consolePrintBoard(genPuzzle); Console.WriteLine("Solved generated puzzle"); SudokuStore.consolePrintBoard(solvedGen); } } break; case 3: for (int example = 0; example < SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES; example++) { initBoard = SudokuStore.getPuzzleExample(example); g = new SudokuGenerator(initBoard, SudokuGenerator.PARAM_DO_NOT_SOLVE); genPuzzle = g.generate(); solverGen = new SudokuSolver(genPuzzle); ErrorCodes.consolePrintlnIfError(solverGen.solve()); solUnq = solverGen.checkIfUniqueSolution(); ErrorCodes.consolePrintlnIfError(solUnq); solvedGen = solverGen.getSolvedBoard(); if ( (solUnq == SudokuSolver.SOLUTION_UNIQUE) && ( SudokuStore.checkPuzzle(genPuzzle) == true ) ) { //SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example board, example: " + example + ", solution unique and correct: YES, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by example board, example: " + example + ", solution unique and correct: NO, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); Console.WriteLine("Generated puzzle"); SudokuStore.consolePrintBoard(genPuzzle); Console.WriteLine("Solved initial board"); SudokuStore.consolePrintBoard(solvedGen); } } break; case 5: initBoard = SudokuPuzzles.PUZZLE_EMPTY; g = new SudokuGenerator(initBoard); genPuzzle = g.generate(); solverGen = new SudokuSolver(genPuzzle); ErrorCodes.consolePrintlnIfError(solverGen.solve()); solUnq = solverGen.checkIfUniqueSolution(); ErrorCodes.consolePrintlnIfError(solUnq); solvedGen = solverGen.getSolvedBoard(); if ( (solUnq == SudokuSolver.SOLUTION_UNIQUE) && ( SudokuStore.checkPuzzle(genPuzzle) == true ) ) { //SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by empty board, solution unique and correct: YES, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by empty board, solution unique and correct: NO, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); Console.WriteLine("Generated puzzle"); SudokuStore.consolePrintBoard(genPuzzle); Console.WriteLine("Solved initial board"); SudokuStore.consolePrintBoard(solvedGen); } break; case 6: initBoard = SudokuPuzzles.PUZZLE_EMPTY; g = new SudokuGenerator(initBoard, SudokuGenerator.PARAM_DO_NOT_SOLVE); if ( g.getGeneratorState() == SudokuGenerator.GENERATOR_INIT_FAILED ) { SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by empty board, solution unique and correct: YES, time (g, s): "); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by empty board, solution unique and correct: NO, time (g, s): "); SudokuStore.consolePrintln("Generator state: " + g.getGeneratorState()); Console.WriteLine(g.getMessages()); } break; case 7: initBoard = SudokuPuzzles.PUZZLE_ERROR; g = new SudokuGenerator(initBoard, SudokuGenerator.PARAM_DO_NOT_SOLVE); if ( g.getGeneratorState() == SudokuGenerator.GENERATOR_INIT_FAILED ) { SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by PUZZLE_ERROR + PARAM_DO_NOT_SOLVE, init failed: YES."); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by PUZZLE_ERROR + PARAM_DO_NOT_SOLVE, init failed: NO."); SudokuStore.consolePrintln("Generator state: " + g.getGeneratorState()); Console.WriteLine(g.getMessages()); } break; case 8: initBoard = SudokuPuzzles.PUZZLE_NON_UNIQUE_SOLUTION; g = new SudokuGenerator(initBoard); genPuzzle = g.generate(); solverGen = new SudokuSolver(genPuzzle); ErrorCodes.consolePrintlnIfError(solverGen.solve()); solUnq = solverGen.checkIfUniqueSolution(); ErrorCodes.consolePrintlnIfError(solUnq); solvedGen = solverGen.getSolvedBoard(); if ( (solUnq == SudokuSolver.SOLUTION_UNIQUE) && ( SudokuStore.checkPuzzle(genPuzzle) == true ) ) { //SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by empty board, solution unique and correct: YES, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by empty board, solution unique and correct: NO, time (g, s): " + g.getComputingTime() + " s., " + solverGen.getComputingTime() + " s., "); Console.WriteLine("Generated puzzle"); SudokuStore.consolePrintBoard(genPuzzle); Console.WriteLine("Solved initial board"); SudokuStore.consolePrintBoard(solvedGen); } break; case 9: initBoard = SudokuPuzzles.PUZZLE_NON_UNIQUE_SOLUTION; g = new SudokuGenerator(initBoard, SudokuGenerator.PARAM_DO_NOT_SOLVE); if ( g.getGeneratorState() == SudokuGenerator.GENERATOR_INIT_FAILED ) { SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by PUZZLE_NON_UNIQUE_SOLUTION + PARAM_DO_NOT_SOLVE, init failed: YES."); } else { testResult = false; SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + ", generate by PUZZLE_NON_UNIQUE_SOLUTION + PARAM_DO_NOT_SOLVE, init failed: NO."); SudokuStore.consolePrintln("Generator state: " + g.getGeneratorState()); Console.WriteLine(g.getMessages()); } break; } if (testResult == true) SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + " >>>>>>>>>>>>>>>>>>>>>> SudokuGenerator, result: OK"); else SudokuStore.consolePrintln("(Thread: " + threadId + ") " + "Test: " + testId + " >>>>>>>>>>>>>>>>>>>>>> SudokuGenerator, result: ERROR"); return testResult; }
/** * Start the Janet-Sudoku Tutorial code. * @param args No arguments are considered. */ public static void Start() { String tmpDir = FileX.getTmpDir(); { /* * Simple sudoku generation. */ SudokuStore.consolePrintln(""); SudokuStore.consolePrintln("Simple sudoku generation."); SudokuGenerator sg = new SudokuGenerator(); int[,] puzzle = sg.generate(); SudokuStore.consolePrintBoard(puzzle); } { /* * Simple sudoku generation + parameters. */ SudokuStore.consolePrintln(""); SudokuStore.consolePrintln("Simple sudoku generation + parameters."); SudokuGenerator sg = new SudokuGenerator(SudokuGenerator.PARAM_GEN_RND_BOARD); int[,] puzzle = sg.generate(); SudokuStore.consolePrintBoard(puzzle); } { /* * Simple sudoku generation + puzzle rating. */ SudokuStore.consolePrintln(""); SudokuStore.consolePrintln("Simple sudoku generation + puzzle rating."); SudokuGenerator sg = new SudokuGenerator(); int[,] puzzle = sg.generate(); int rating = SudokuStore.calculatePuzzleRating(puzzle); SudokuStore.consolePrintBoard(puzzle); SudokuStore.consolePrintln("Puzzle rating: " + rating); } { /* * Solving sudoku example. */ SudokuStore.consolePrintln(""); SudokuStore.consolePrintln("Solving sudoku example."); SudokuSolver ss = new SudokuSolver(SudokuPuzzles.PUZZLE_EXAMPLE_001); SudokuStore.consolePrintBoard(ss.getBoard()); ss.solve(); SudokuStore.consolePrintBoard(ss.getSolvedBoard()); } { /* * Saving board examples */ SudokuStore.consolePrintln(""); SudokuStore.consolePrintln("Saving board examples " + tmpDir); SudokuStore.saveBoard(SudokuPuzzles.PUZZLE_EXAMPLE_001, tmpDir + "sudoku-board-ex-1.txt"); SudokuStore.saveBoard(SudokuPuzzles.PUZZLE_EXAMPLE_001, tmpDir + "sudoku-board-ex-2.txt", "This is a head comment"); SudokuStore.saveBoard(SudokuPuzzles.PUZZLE_EXAMPLE_001, tmpDir + "sudoku-board-ex-3.txt", "This is a head comment", "And a tail comment"); SudokuSolver ss = new SudokuSolver(1); ss.solve(); ss.saveSolvedBoard(tmpDir + "sudoku-board-ex-sol.txt", "Solution for the PUZZLE_EXAMPLE_001"); } { /* * Puzzle modification - i.e. rotation */ SudokuStore.consolePrintln("----------------------------------------------------"); SudokuStore.consolePrintln(">>>>>>>> Puzzle modification"); int[,] puzzle = SudokuStore.getPuzzleExample(0); int[,] puzzleRotated = SudokuStore.rotateClockWise(puzzle); SudokuStore.consolePrintBoard(puzzle); SudokuStore.consolePrintBoard(puzzleRotated); } /* * And many other staff provided by the library :-) */ }
/** * Generates random puzzle with unique solution. * Evaluates puzzle difficulty rating. * * @see SudokuGenerator * @see SudokuGenerator#PARAM_GEN_RND_BOARD * @see SudokuGenerator#generate() * @see SudokuStore#calculatePuzzleRating(int[,]) */ private void generateAndRateRandomPuzzle() { generator = new SudokuGenerator(SudokuGenerator.PARAM_GEN_RND_BOARD); setGeneratorOptions(); int[,] generated = generator.generate(); if (generator.getGeneratorState() == SudokuGenerator.GENERATOR_GEN_FINISHED) { trackPuzzleUndo(); puzzle = generated; ratePuzzleDifficulty(); } else { JanetConsole.println(">>> !!! Error while generating random puzzle !!! <<<"); JanetConsole.println(generator.getMessages()); } }
/** * Generates puzzle based on current puzzle * (different puzzle, same solution). * * @see SudokuGenerator * @see SudokuGenerator#PARAM_DO_NOT_TRANSFORM * @see SudokuGenerator#generate() */ private void generateFromCurrentPuzzle() { generator = new SudokuGenerator(puzzle, SudokuGenerator.PARAM_DO_NOT_TRANSFORM); setGeneratorOptions(); int[,] generated = generator.generate(); if (generator.getGeneratorState() == SudokuGenerator.GENERATOR_GEN_FINISHED) { trackPuzzleUndo(); puzzle = generated; } else { JanetConsole.println(">>> !!! Error while generating puzzle !!! <<<"); JanetConsole.println(generator.getMessages()); } }