Exemplo n.º 1
0
        public static void Main(string [] args)
        {
            var numerBoardTokenizer = new NumberBoardTokenizer();

            using (var streamReader = new StreamReader(new FileStream("./question.txt", FileMode.Open)))
            {
                using (var streamWriter = new StreamWriter(new FileStream("./answer.txt", FileMode.OpenOrCreate)))
                {
                    var lines = streamReader.ReadToEnd().Split(new[] {Environment.NewLine},
                                                               StringSplitOptions.RemoveEmptyEntries);
                    for (var index = 0; index < lines.Length; index += 10)
                    {
                        var header = lines[index];
                        Console.WriteLine(header);
                        streamWriter.WriteLine(header);
                        var generate = numerBoardTokenizer.Generate(string.Join("", lines, index + 1, 9));
                        var sudokuBoard = new SudokuBoard();
                        sudokuBoard.Make(generate);
                        streamWriter.WriteLine(sudokuBoard.Answer);
                        sudokuBoard.Solve();
                        streamWriter.WriteLine(sudokuBoard.Answer);
                    }
                }
            }
        }
Exemplo n.º 2
0
    void Awake()
    {
        sudokuBoard = GameObject.FindObjectOfType<SudokuBoard>();
        modPanel = GameObject.FindObjectOfType<ModifierPanel>();

        DontDestroyOnLoad(this.gameObject);
    }
	void Awake() {
		int[,] boardArr;

		var spaceArr = new ISpace<Tiles>[dims, dims];
		board = new TileSudokuBoard((int) dims, spaceArr);

		switch (SceneManager.GetActiveScene().name) {
		case "Tutorial":
			boardArr = tutorialBoard;
			board.EndPos = new int[] {2, 2};
			break;
		case "MainGame":
		default:
			Debug.Log ("name is " + SceneManager.GetActiveScene().name);
			boardArr = normalBoard;
			break;
		}


		if (prefab==null)
			throw new System.Exception("missing spacewrapper prefab");
		//var spaceArr = new ISpace<Tiles>[dims, dims];
		for (var i = 0; i < dims; ++i)
			for (var j = 0; j < dims; ++j) {
				spaceArr [i, j] = CreateSpaceWrapper (i, j, (Tiles)boardArr [i, j]);
				Debug.Log ("Set Tile " + boardArr [i, j].ToString () + " at position" + i.ToString () + ", " + j.ToString());

			}
	}
 void Awake()
 {
     if (prefab==null)
         throw new System.Exception("missing spacewrapper prefab");
     var spaceArr = new ISpace<Tiles>[dims, dims];
     for (var i=0; i<dims; ++i)
         for (var j=0; j<dims; ++j)
             spaceArr[i,j] = CreateSpaceWrapper(i,j);
     board = new TileSudokuBoard((int) dims, spaceArr);
 }
Exemplo n.º 5
0
    public void startGame()
    {
        sudokuBoard = GameObject.FindObjectOfType<SudokuBoard>();
        modPanel = GameObject.FindObjectOfType<ModifierPanel>();

        modPanel.reset();
        sudokuBoard.instantiateBoard();
        populateBoard(level);
        sudokuBoard.checkBoard();
    }
        /// <summary>
        /// Finds the next position by finding the next blank character, 
        /// going from top to bottom, left to right
        /// </summary>
        /// <param name="sudokuBoard">SudokuBoard to find the next position for</param>
        /// <returns>Position of the next blank character if one is found, null otherwise</returns>
        protected override Position FindNextPosition(SudokuBoard sudokuBoard)
        {
            for (var row = 0; row < SudokuBoard.Rows; row++)
            {
                for (var col = 0; col < SudokuBoard.Columns; col++)
                {
                    if (sudokuBoard[col, row] == '-')
                    {
                        return new Position(col, row);
                    }
                }
            }

            return null;
        }
Exemplo n.º 7
0
    // Use this for initialization
    void Start()
    {
        sudokuBoard = GameObject.FindObjectOfType<SudokuBoard>();
        modPanel = GameObject.FindObjectOfType<ModifierPanel>();

        sudokuBoard.instantiateBoard();
        int[] modifiers = createModifiers(4);
        foreach (int mod in modifiers)
        {
            int x = Random.Range(0, 9);
            int y = Random.Range(0, 9);

            while (sudokuBoard.getValue(x, y) - mod < 0 || sudokuBoard.getValue(x, y) - mod > 8)
                x = Random.Range(0, 9);
                y = Random.Range(0, 9);

            sudokuBoard.initializeMod(mod, x, y);
            modPanel.addMod(mod);
        }
    }
 public void Test_SolveBoardIterativelyWithQueue()
 {
     try
     {
         SudokuBoard board = new SudokuBoard();
         if (Program.SolveBoardIterativelyWithQueue(ref board))
         {
             if (!board.VerifyBoard())
             {
                 Assert.Fail("SolveBoardIterativelyWithQueue() returned true, but VerifyBoard() returned false afterwards.");
             }
         }
         else
         {
             Assert.Fail("SolveBoardIterativelyWithQueue() returned false.");
         }
     }
     catch (Exception e)
     {
         Assert.Fail("Test_SolveBoardIterativelyWithQueue() threw an exception. " + e.Message);
     }
 }
Exemplo n.º 9
0
        public void TestValidate()
        {
            SudokuBoard board  = new SudokuBoard();
            Validity    valid1 = BoardValidation.Validate(board);

            Assert.AreEqual(Validity.CONSISTENT, valid1);

            BoardFactory.FillSequential(board);
            Validity valid2 = BoardValidation.Validate(board);

            Assert.AreEqual(Validity.INCONSISTENT, valid2);

            BoardFactory.FillStriped(board);
            Validity valid3 = BoardValidation.Validate(board);

            Assert.AreEqual(Validity.COMPLETE, valid3);

            board[3] = 15;
            Validity valid4 = BoardValidation.Validate(board);

            Assert.AreEqual(Validity.INVALID, valid4);
        }
Exemplo n.º 10
0
        public static SudokuBoard CreateBoard(SudokuTestDifficulty difficulty)
        {
            string sudokuToParse;

            switch (difficulty)
            {
            case SudokuTestDifficulty.VeryEasy:
                sudokuToParse = _veryEasySudokuString;
                break;

            case SudokuTestDifficulty.Easy:
                sudokuToParse = _easySudokuString;
                break;

            case SudokuTestDifficulty.Medium:
                sudokuToParse = _mediumSudokuString;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(difficulty), difficulty, null);
            }
            return(SudokuBoard.Parse(sudokuToParse));
        }
Exemplo n.º 11
0
        public void When_Board_Is_Valid_Then_Should_Get_Any_Cell(int row, int column, int value)
        {
            // arrange
            var board = new[, ]
            {
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
            };
            var sudokuBoard = new SudokuBoard(board);

            // act
            var cell = sudokuBoard[row, column];

            // assert
            cell.Should().Be(value);
        }
Exemplo n.º 12
0
        public void UnsolvedBoard_SolvedBoardReturned()
        {
            //arrange
            int[] expectedResult = new int[]
            {
                8, 2, 7, 3, 1, 6, 5, 4, 9, 6, 4, 9, 7, 5, 2, 8, 3, 1, 5, 3, 1, 4, 8, 9, 6, 7, 2,
                4, 9, 6, 2, 3, 8, 1, 5, 7, 2, 1, 8, 5, 4, 7, 3, 9, 6, 7, 5, 3, 6, 9, 1, 2, 8, 4,
                3, 7, 4, 1, 6, 5, 9, 2, 8, 9, 6, 2, 8, 7, 3, 4, 1, 5, 1, 8, 5, 9, 2, 4, 7, 6, 3
            };
            SudokuBoard testBoard = new SudokuBoard(new int[] { 8, 2, 0, 3, 0, 0, 0, 0, 9, 0, 0, 9, 7, 5, 0, 8, 0, 0, 0, 3, 0, 0, 8, 0, 6, 0, 0,
                                                                0, 0, 6, 2, 3, 0, 0, 0, 7, 2, 1, 8, 5, 4, 7, 0, 0, 0, 7, 0, 0, 0, 9, 0, 0, 8, 0,
                                                                0, 0, 4, 1, 0, 5, 0, 0, 8, 0, 6, 0, 0, 7, 0, 4, 1, 0, 0, 0, 5, 9, 0, 4, 7, 6, 3 });
            BacktrackBoardSolver solver = new BacktrackBoardSolver();

            //act
            Result <int[]> result = solver.Solve(testBoard);

            //assert
            Assert.IsTrue(result.IsSuccess);
            bool areEqual = AreEqual(expectedResult, result.Data);

            Assert.IsTrue(areEqual);
        }
Exemplo n.º 13
0
        public static SudokuBoard LoadBoardFromText(string text)
        {
            var board = new SudokuBoard();
            int row   = 0;

            foreach (var line in text.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries))
            {
                int col = 0;
                foreach (var c in line.Trim('\r').ToCharArray())
                {
                    if (c != ' ' && c != '.')
                    {
                        board.SetValue(board[row, col], int.Parse(c.ToString()));
                    }

                    col++;
                }

                row++;
            }

            return(board);
        }
        public void SudokoBoard_Solve_ExtraZonesWithSolution()
        {
            // Arrange
            // http://en.wikipedia.org/wiki/File:Oceans_Hypersudoku18_Puzzle.svg
            SudokuBoard board = SudokuFactory.ClassicWith3x3BoxesAndHyperRegions(new[]
            {
                ".......1.",
                "..2....34",
                "....51...",
                ".....65..",
                ".7.3...8.",
                "..3......",
                "....8....",
                "58....9..",
                "69......."
            });

            string[] tileDefinitions = new[]
            {
                "946832715",
                "152697834",
                "738451296",
                "819726543",
                "475319682",
                "263548179",
                "327985461",
                "584163927",
                "691274358"
            };

            // Act
            IEnumerable <SudokuBoard> solutions = board.Solve();

            // Assert
            Assert.Single(solutions);
            Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);
        }
Exemplo n.º 15
0
        public static double Eval(IChromosome sudokuChromosome, SudokuBoard sudokuBoard, int populationSize, double fitnessThreshold, int generationNb)
        {
            var fitness   = new SudokuFitness(sudokuBoard);
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation();

            var population = new Population(populationSize, populationSize, sudokuChromosome);
            var ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new OrTermination(new ITermination[]
                {
                    new FitnessThresholdTermination(fitnessThreshold),
                    new GenerationNumberTermination(generationNb)
                })
            };

            ga.Start();

            var bestIndividual = ((ISudokuChromosome)ga.Population.BestChromosome);
            var solutions      = bestIndividual.GetSudokus();

            return(solutions.Max(solutionSudoku => fitness.Evaluate(solutionSudoku)));
        }
Exemplo n.º 16
0
        public void GuessMakeFirstGuessTest()
        {
            int[,] start =
            {
                { 0, 0 },
                { 0, 0 }
            };
            int[,] endOne =
            {
                { 1, 0 },
                { 0, 0 }
            };
            int[,] endTwo =
            {
                { 2, 0 },
                { 0, 0 }
            };
            systemUnderTest = new SudokuBoard(start, SudokuBoard.BoardProperty.TwoByTwo);

            systemUnderTest.MakeGuess();
            int[,] outcome = systemUnderTest.GetAsMultidimentionalArray();

            Assert.IsTrue(EqualTwoDimentionalArray(outcome, endOne) || EqualTwoDimentionalArray(outcome, endTwo));
        }
Exemplo n.º 17
0
        public override void Draw()
        {
            var         buffer            = Context.Buffer;
            var         layout            = Context.Layout;
            var         population        = Context.Population;
            SudokuBoard sudokuBoardToDraw = null;

            if (population != null)
            {
                if ((population.BestChromosome is ISudokuChromosome bestChromosome))
                {
                    if (population.CurrentGeneration != null)
                    {
                        var stats = population.CurrentGeneration.Chromosomes.GroupBy(c => c.Fitness).OrderByDescending(g => g.Key).Select(g => new { Fitness = g.Key, Count = g.Count(), First = ((ISudokuChromosome)g.First()).GetSudokus().First(), Last = ((ISudokuChromosome)g.Last()).GetSudokus().First() }).ToList();
                        Context.WriteText($"Fitness,Count:({stats[0].Fitness},{stats[0].Count})...({stats[stats.Count / 3].Fitness},{stats[stats.Count / 3].Count})...({stats[stats.Count * 2 / 3].Fitness},{stats[stats.Count * 2 / 3].Count})...({stats[stats.Count - 1].Fitness},{stats[stats.Count - 1].Count})");
                        Context.WriteText($"Top: [{string.Join(",", stats[0].First.Cells.Take(9).Select(i => i.ToString()).ToArray())}] [{string.Join(",", stats[0].Last.Cells.Take(9).Select(i => i.ToString()).ToArray())}]");
                        if (stats.Count > 1)
                        {
                            Context.WriteText($"Next: [{string.Join(",", stats[1].First.Cells.Take(9).Select(i => i.ToString()).ToArray())}] [{string.Join(",", stats[1].Last.Cells.Take(9).Select(i => i.ToString()).ToArray())}]");
                        }
                    }
                    sudokuBoardToDraw = bestChromosome.GetSudokus().First();
                }
                else
                {
                    if (population.BestChromosome is MultipleChromosome multiChromosome)
                    {
                        var orderedSubChromosomes = multiChromosome.Chromosomes.OrderByDescending(c => c.Fitness).ToList();
                        bestChromosome = (ISudokuChromosome)orderedSubChromosomes.First();
                        var worstChromosome = (ISudokuChromosome)orderedSubChromosomes.Last();
                        sudokuBoardToDraw = bestChromosome.GetSudokus().First();
                        Context.WriteText($"Best Chromosome Best Sub-Fitness: {((IChromosome)bestChromosome).Fitness}");
                        Context.WriteText($"Best Chromosome Worst Sub-Fitness:: {((IChromosome)worstChromosome).Fitness}");
                    }
                }
            }
Exemplo n.º 18
0
        public void HorisontalExclusionOnOnlyPositionsThatFit()
        {
            int[,] start =
            {
                { 1, 0, 0, 0 },
                { 0, 4, 0, 0 },
                { 3, 0, 0, 0 },
                { 0, 0, 0, 0 }
            };
            int[,] end =
            {
                { 1, 3, 0, 0 },
                { 0, 4, 0, 0 },
                { 3, 0, 0, 0 },
                { 4, 0, 0, 0 }
            };
            systemUnderTest = new SudokuBoard(start, SudokuBoard.BoardProperty.FourByFour);

            systemUnderTest.SimpleSquareExclusion();
            systemUnderTest.HorizontalExclusionOnOnlyPositionsThatFit();
            int[,] outcome = systemUnderTest.GetAsMultidimentionalArray();

            Assert.IsTrue(EqualTwoDimentionalArray(outcome, end));
        }
        private void PasteFromClipboard()
        {
            if (!Clipboard.ContainsText())
            {
                return;
            }

            SudokuBoard board = new SudokuBoard(Clipboard.GetText());

            if (board != null)
            {
                Cursor.Current = Cursors.WaitCursor;

                try
                {
                    solutionsTree.InitTree(board);
                    UndoRedoManager.Instance.Clear();
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }
        public void SudokuBoard_Solve_ClassicWithSolution()
        {
            // Arrange
            SudokuBoard board = SudokuFactory.ClassicWith3x3Boxes(new[]
            {
                "...84...9",
                "..1.....5",
                "8...2146.",
                "7.8....9.",
                ".........",
                ".5....3.1",
                ".2491...7",
                "9.....5..",
                "3...84..."
            });

            string[] tileDefinitions = new[]
            {
                "632845179",
                "471369285",
                "895721463",
                "748153692",
                "163492758",
                "259678341",
                "524916837",
                "986237514",
                "317584926",
            };

            // Act
            IEnumerable <SudokuBoard> solutions = board.Solve();

            // Assert
            Assert.Single(solutions);
            Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);
        }
Exemplo n.º 21
0
 public override void Undo()
 {
     SudokuBoard.ChangeText(Row, Column, PreviousValue);
     SudokuBoard.SelectSquare(Row, Column);
 }
Exemplo n.º 22
0
 public static SudokuBoard BacktrackingSearch(SudokuBoard sb)
 {
     return(RecursiveBacktracking(sb));
 }
Exemplo n.º 23
0
        public SudokuBoard Solve(SudokuBoard sourceBoard)
        {
            var visited = new Stack <Cell>();
            var toVisit = new Stack <Cell>();

            sourceBoard.Where(cell => !cell.IsEmpty)
            .ToList()
            .ForEach(cell => visited.Push(cell));

            var sudoku = new SudokuBoard(visited);

            if (!sudoku.EmptyCells.Any())
            {
                return(sudoku);
            }

            var firstEmpty = sudoku.EmptyCells.First();

            var start = Enumerable
                        .Range(1, 9)
                        .Shuffle()
                        .First(x => sudoku.IsValid(new Cell(firstEmpty.Row, firstEmpty.Col, x)));


            toVisit.Push(new Cell(firstEmpty.Row, firstEmpty.Col, start));

            while (toVisit.Any())
            {
                var current = toVisit.Pop();
                visited.Push(current);

                sudoku = new SudokuBoard(visited);
                if (!sudoku.EmptyCells.Any())
                {
                    return(sudoku);
                }

                current = sudoku.EmptyCells.First();

                var neighbours = Enumerable.Range(1, 9)
                                 .Shuffle()
                                 .Where(x => sudoku.IsValid(new Cell(current.Row, current.Col, x)))
                                 .Select(x => new Cell(current.Row, current.Col, x))
                                 .ToList();

                // Backtracking part
                if (!neighbours.Any())
                {
                    if (!toVisit.Any())
                    {
                        break;
                    }

                    var next = toVisit.Peek();
                    while (visited.Any(cell => cell.Row == next.Row && cell.Col == next.Col))
                    {
                        visited.Pop();
                    }
                }
                // Classic DFS
                else
                {
                    neighbours.ForEach(toVisit.Push);
                }
            }

            return(sudoku);
        }
Exemplo n.º 24
0
 private void LoadData()
 {
     sb = new SudokuBoard(Canvas1.Children);
     Canvas1.Children.Clear();
 }
Exemplo n.º 25
0
    public static bool ValidateSolution(int[][] board)
    {
        var sudoku = new SudokuBoard(board);

        return(sudoku.IsValid());
    }
Exemplo n.º 26
0
        /*
         * For each cell value 1 - 9,
         * Get All cells that have candidates for the current value.
         * Start with Xwing of size one and continue up to 9
         *  - for each row/column
         *  - are the row/column candidates less than or equal to the XWing size we're looking for?
         *  - if yes, this row MIGHT be an XWing Set candidate.
         *    - Are there at least "setSize" row/column(s) that
         *        a) have less than or equal to the number of elements in our xwing set candidate
         *        b) every value in the row/column exist in the candidate row/column
         *        If yes, we have an Xwing!
         *        - out of all the rows that meet this criteria, skip the first "setSize", and take the rest
         *        - remove candidate values from the rest of the rows, ONLY IN THE SAME COLUMNS AS THE CANDIDATE ROW/Column
         *    */
        protected override bool DoCrank(ref SudokuBoard board)
        {
            bool modified = false;

            foreach (int currentValue in SudokuBoard.CELL_VALUES)
            {
                var candidateCells = board.Cells.Where(c => c.Candidates.Contains(currentValue)).ToList();

                var boardRows    = board.Cells.GroupBy(the => the.Row).ToArray();
                var boardColumns = board.Cells.GroupBy(the => the.Column).ToArray();

                var candidateRows    = candidateCells.GroupBy(c => c.Row);
                var candidateColumns = candidateCells.GroupBy(c => c.Column);

                var uniqueColumns = candidateCells.Select(c => c.Column).Distinct().ToList();
                var uniqueRows    = candidateCells.Select(c => c.Row).Distinct().ToList();

                //that is, the column values to test for the sudukoboard rows
                var rowSets = this.GetPowerSet(uniqueColumns).Distinct();

                //vice versa
                var colSets = this.GetPowerSet(uniqueRows).Distinct();


                foreach (int xWingSize in SudokuBoard.CELL_VALUES)
                {
                    var xWingTestRows = rowSets.Where(r => r.Count() == xWingSize).ToArray();
                    foreach (var xWingValues in xWingTestRows)
                    {
                        int rowCount   = xWingValues.Count();
                        var rowsToTest = candidateRows.Where(r => xWingValues.Contains(r.Key)).ToArray();
                        if (rowsToTest.Length < rowCount)
                        {
                            continue;
                        }

                        var setUnionOfCandidateColumns = rowsToTest.SelectMany(r => r.Select(c => c.Column)).Distinct().ToArray();
                        if (setUnionOfCandidateColumns.Length != rowCount)
                        {
                            continue;
                        }
                        var xWingTrimColumns = boardColumns.Where(clmn => setUnionOfCandidateColumns.Contains(clmn.Key)).ToArray();
                        foreach (var trimCol in xWingTrimColumns)
                        {
                            var trimCells = trimCol.Where(c => !xWingValues.Contains(c.Row) && c.Candidates.Contains(currentValue)).ToArray();
                            foreach (var cell in trimCells)
                            {
                                modified |= cell.Candidates.Remove(currentValue);
                            }
                        }
                        break;
                    }

                    //now do it for columns
                    var xWingTestCols = colSets.Where(clmn => clmn.Count() == xWingSize).ToArray();
                    foreach (var xWingValues in xWingTestCols)
                    {
                        int colCount      = xWingValues.Count();
                        var columnsToTest = candidateColumns.Where(clmn => xWingValues.Contains(clmn.Key)).ToArray();
                        if (columnsToTest.Length < colCount)
                        {
                            continue;
                        }

                        var setUnionOfCandidateRows = columnsToTest.SelectMany(clmn => clmn.Select(c => c.Row)).Distinct().ToArray();
                        if (setUnionOfCandidateRows.Length != colCount)
                        {
                            continue;
                        }

                        var xWingTrimRows = boardRows.Where(r => setUnionOfCandidateRows.Contains(r.Key)).ToArray();

                        foreach (var trimRow in xWingTrimRows)
                        {
                            var trimCells = trimRow.Where(c => !xWingValues.Contains(c.Column) && c.Candidates.Contains(currentValue)).ToArray();
                            foreach (var cell in trimCells)
                            {
                                modified |= cell.Candidates.Remove(currentValue);
                            }
                        }
                        break;
                    }
                }
            }

            return(modified);
        }
        public void SudokoBoard_Solve_SamuraiWithSolution()
        {
            // Arrange
            // http://www.freesamuraisudoku.com/1001HardSamuraiSudokus.aspx?puzzle=42
            SudokuBoard board = SudokuFactory.Samurai(new[]
            {
                "6..8..9..///.....38..",
                "...79....///89..2.3..",
                "..2..64.5///...1...7.",
                ".57.1.2..///..5....3.",
                ".....731.///.1.3..2..",
                "...3...9.///.7..429.5",
                "4..5..1...5....5.....",
                "8.1...7...8.2..768...",
                ".......8.23...4...6..",
                "//////.12.4..9.//////",
                "//////......82.//////",
                "//////.6.....1.//////",
                ".4...1....76...36..9.",
                "2.....9..8..5.34...81",
                ".5.873......9.8..23..",
                "...2....9///.25.4....",
                "..3.64...///31.8.....",
                "..75.8.12///...6.14..",
                ".......2.///.31...9..",
                "..17.....///..7......",
                ".7.6...84///8...7..5."
            });

            string[] tileDefinitions = new[]
            {
                "674825931000142673859",
                "513794862000897425361",
                "982136475000563189472",
                "357619248000425916738",
                "298457316000918357246",
                "146382597000376842915",
                "469578123457689534127",
                "821963754689231768594",
                "735241689231754291683",
                "000000512748396000000",
                "000000497163825000000",
                "000000368592417000000",
                "746921835976142368597",
                "238456971824563497281",
                "159873246315978152346",
                "815237469000625749813",
                "923164758000314825769",
                "467598312000789631425",
                "694385127000431586972",
                "581742693000257914638",
                "372619584000896273154"
            };

            // Act
            IEnumerable <SudokuBoard> solutions = board.Solve();

            // Assert
            Assert.Single(solutions);
            Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);
        }
Exemplo n.º 28
0
 public SudokuEngine(SudokuBoard sudokuBoard, SudokuMapper sudokuMapper)
 {
     _sudokuBoard  = sudokuBoard;
     _sudokuMapper = sudokuMapper;
 }
Exemplo n.º 29
0
 public void InitTree(SudokuBoard a_board)
 {
     UpdateTree(SudokuSolutionNode.CreateRoot(a_board));
 }
Exemplo n.º 30
0
 public SudokuBoard BacktrackingSearch(SudokuBoard sb)
 {
     this.sudokuBoard = sb;
     this.length      = sb.Board.GetLength(0);
     return(RecursiveBacktracking());
 }
Exemplo n.º 31
0
        private static (SudokuBoard board, bool finish, bool deadEnd) generateBoardFromCell(int cellNumber, SudokuBoard board)
        {
            // var possibleValuesShuffled = Helpers.determinePossibleValuesx(cellNumber, board).Shuffle_knuthfisheryates2();
            var possibleValuesShuffled = Helpers.determinePossibleValuesx(cellNumber, board).Shuffle_knuthfisheryates2();

            // for (var index = 0; index < possibleValuesShuffled.Length; index++)
            foreach (var possibleValue in possibleValuesShuffled)
            {
                var nextBoard = Helpers.sudokuBoardClone(board);

                // nextBoard.cells[cellNumber].value = possibleValuesShuffled[index];
                nextBoard.cells[cellNumber].value         = possibleValue;
                nextBoard.cells[cellNumber].expectedValue = nextBoard.cells[cellNumber].value;
                nextBoard.cells[cellNumber].seed          = true;

                var nextCellNumber = cellNumber + 1;
                if (nextCellNumber == board.cells.Length)
                {
                    return(board : nextBoard, finish : true, deadEnd : false);
                }

                var(finishedBoard, finish, deadEnd) = generateBoardFromCell(nextCellNumber, nextBoard);
                if (finish)
                {
                    return(board : finishedBoard, finish : true, deadEnd : deadEnd);
                }
            }

            // all cell values are wrong
            return(board : null, finish : false, deadEnd : true);
        }
Exemplo n.º 32
0
 public SudokuSolverTest()
 {
     this.boardInstance         = new SudokuBoard();
     this.boardReaderInstance   = new StringBoardReaderStrategy(TestCaseInitial);
     this.boardBruteForceSolver = new BruteForceSudokuSolver();
 }
Exemplo n.º 33
0
        private async void button11_Click(object sender, EventArgs e)
        {
            bool labelValue = false;

            // go through all labels and if there are no label values
            // then cannot attempt solution
            // got some value so attempt to solve
            int[,] board = new int[Settings.BOARD_SIZE, Settings.BOARD_SIZE];

            for (int j = 0; j < Settings.BOARD_SIZE; j++)
            {
                for (int i = 0; i < Settings.BOARD_SIZE; i++)
                {
                    if (cellLabels[i, j].Text == string.Empty)
                    {
                        board[i, j] = 0;
                    }
                    else
                    {
                        labelValue  = true;
                        board[i, j] = Convert.ToInt32(cellLabels[i, j].Text);
                    }
                }
            }

            if (labelValue)
            {
                SudokuBoard sb = new SudokuBoard(board);
                //MessageBox.Show( sb.Board.ToString() );

                // set buttons to disabled
                button11.Enabled = false;
                this.Cursor      = Cursors.WaitCursor;

                bool result = false;
                if (rdoBrute.Checked)
                {
                    result = await Task.Run(() => sb.Solve(this, chkSingle.Checked));
                }
                else
                {
                    result = await Task.Run(() => sb.TargettedSolve(this, chkSingle.Checked));
                }

                button11.Enabled = true;
                this.Cursor      = Cursors.Default;

                if (result)
                {
                    for (int j = 0; j < Settings.BOARD_SIZE; j++)
                    {
                        for (int i = 0; i < Settings.BOARD_SIZE; i++)
                        {
                            cellLabels[i, j].Text = String.Format("{0}", sb.Solution.Board[i, j]);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("No Solution Found");
                }

                labelValid.Text    = sb.Valid.ToString();
                labelAttempts.Text = sb.Attempts.ToString();
                labelTime.Text     = sb.TimeTaken.ToString();
            }
        }
Exemplo n.º 34
0
        public override Widget CreateConfigWidget()
        {
            var container = new VBox();



            var fileHBox = new HBox();

            container.Add(fileHBox);


            // Sudoku index.
            var indexHBox = new HBox();

            fileHBox.Add(indexHBox);
            var indexLabel = new Label {
                Text = "Sudoku index"
            };

            indexHBox.Add(indexLabel);

            var indexButton = new SpinButton(1, _sudokuList.Count, 1)
            {
                Value = 1
            };

            indexButton.ValueChanged += delegate
            {
                _sudokuIndex = (int)indexButton.Value - 1;

                OnReconfigured();
            };
            indexHBox.Add(indexButton);

            // File support

            var selectImageButton = new Button {
                Label = "Load sudoku(s) file"
            };

            selectImageButton.Clicked += delegate
            {
                Gtk.FileChooserDialog filechooser =
                    new Gtk.FileChooserDialog(
                        "Select the sudoku to use",
                        Context.GtkWindow,
                        FileChooserAction.Open,
                        "Cancel",
                        ResponseType.Cancel,
                        "Open",
                        ResponseType.Accept);

                if (filechooser.Run() == (int)ResponseType.Accept)
                {
                    _sudokuList = SudokuBoard.ParseFile(filechooser.Filename);
                    indexButton.SetRange(1, _sudokuList.Count);
                }

                filechooser.Destroy();

                OnReconfigured();
            };
            fileHBox.Add(selectImageButton);
            var helpImageButton = new Button {
                Label = "?"
            };

            helpImageButton.Clicked += delegate
            {
                var msg = new MessageDialog(
                    Context.GtkWindow,
                    DialogFlags.Modal,
                    MessageType.Info,
                    ButtonsType.Ok,
                    "Accepted formats represent Sudokus on one or several lines," +
                    "\n with characters '.', '-', or 'X' for empty cells and digits otherwise." +
                    "\n Lines starting with other characters are ignored such as '#' for comments on the common sdk format.");
                msg.Run();

                msg.Destroy();
            };
            fileHBox.Add(helpImageButton);



            // Genetics selector.

            var geneticsHBox = new HBox();

            geneticsHBox.Spacing += 2;

            var geneticsLabel = new Label {
                Text = "Genetics"
            };

            geneticsHBox.Add(geneticsLabel);

            var chromosomeTypes = new string[] {
                nameof(SudokuChromosomeType.RowsPermutations)
                , nameof(SudokuChromosomeType.Cells)
                , nameof(SudokuChromosomeType.RandomRowsPermutations)
                , nameof(SudokuChromosomeType.RowsWithoutMask)
                , nameof(SudokuChromosomeType.CellsWithoutMask)
            };

            _nbPermsHBox = new HBox
            {
                Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations)
            };


            var nbPermsLabel = new Label {
                Text = "Nb Permutations"
            };

            _nbPermsHBox.Add(nbPermsLabel);

            var nbPermsButton = new SpinButton(1, 1000, 1);

            _nbPermsHBox.Add(nbPermsButton);
            nbPermsButton.Value         = _nbPermutations;
            nbPermsButton.ValueChanged += delegate
            {
                _nbPermutations = (int)nbPermsButton.Value;

                OnReconfigured();
            };

            var nbSudokusLabel = new Label {
                Text = "Nb Sudokus"
            };

            _nbPermsHBox.Add(nbSudokusLabel);

            var nbSudokusButton = new SpinButton(1, 1000, 1);

            _nbPermsHBox.Add(nbSudokusButton);
            nbSudokusButton.Value         = _nbSudokus;
            nbSudokusButton.ValueChanged += delegate
            {
                _nbSudokus = (int)nbSudokusButton.Value;

                OnReconfigured();
            };



            var selectorCombo = new ComboBox(chromosomeTypes)
            {
                Active = 0
            };

            selectorCombo.Changed += delegate
            {
                _ChromosomeType      = selectorCombo.ActiveText;
                _nbPermsHBox.Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations);
                OnReconfigured();
            };
            geneticsHBox.Add(selectorCombo);
            container.Add(geneticsHBox);
            container.Add(_nbPermsHBox);

            //Multi check
            var multiHBox  = new HBox();
            var multiCheck = new CheckButton("Multi-Solutions")
            {
                Active = _multipleChromosome
            };

            _nbChromosomesHBox          = new HBox();
            _nbChromosomesHBox.Spacing += 2;
            _nbChromosomesHBox.Visible  = _multipleChromosome;

            var nbChromosomesLabel = new Label {
                Text = "Nb Chrom."
            };

            _nbChromosomesHBox.Add(nbChromosomesLabel);

            var nbChromosomesButton = new SpinButton(1, 1000, 1);

            _nbChromosomesHBox.Add(nbChromosomesButton);
            nbChromosomesButton.Value         = _nbChromosomes;
            nbChromosomesButton.ValueChanged += delegate
            {
                _nbChromosomes = (int)nbChromosomesButton.Value;

                OnReconfigured();
            };

            multiCheck.Toggled += delegate
            {
                _multipleChromosome        = multiCheck.Active;
                _nbChromosomesHBox.Visible = _multipleChromosome;

                OnReconfigured();
            };

            multiHBox.Add(multiCheck);
            multiHBox.Add(_nbChromosomesHBox);

            container.Add(multiHBox);

            return(container);
        }
Exemplo n.º 35
0
        public static (SudokuBoard board, bool finish, bool resolved) resolverWorkForce(int cellNumber, SudokuBoard board)
        {
            // console.log(`resolverWorkForce: cell:${cellNumber}`);
            // sortir de la recurrence
            if (cellNumber >= board.cells.Length)
            {
                return(board : board, finish : true, resolved : true);
            }

            // if (board.cells[cellNumber].value != null)
            // TODO checkf this modification does not create problem
            // TODO replace null by 0
            // TODO
            // TODO
            // TODO
            // TODO
            // TODO
            // TODO
            // TODO
            if (board.cells[cellNumber].value != 0)
            {
                // the cell is already filled we continue recurrence
                // console.log(`resolverWorkForce: ALREADY FILLED - cell:${cellNumber} - value:${board.cells[cellNumber].value}`);
                return(resolverWorkForce(cellNumber + 1, board));
            }
            else
            {
                // console.log(`resolverWorkForce: NO VALUE DEFINED cell:${cellNumber} - value:${board.cells[cellNumber].value}`);

                // liste of potential values for the cell
                var possibleValuesShuffled = Helpers.determinePossibleValuesx(cellNumber, board).Shuffle_knuthfisheryates2();

                // parse all the potential values
                // for (var index = 0; index < possibleValuesShuffled.Length; index++)
                foreach (var possibleValue in possibleValuesShuffled)
                {
                    var nextBoard = Helpers.sudokuBoardClone(board);

                    // nextBoard.cells[cellNumber].value = possibleValuesShuffled[index];
                    nextBoard.cells[cellNumber].value = possibleValue;

                    // console.log(`resolverWorkForce: PROPOSE VALUE cell:${cellNumber} - value:${nextBoard.cells[cellNumber].value}`);

                    var(finishedBoard, finish, resolved) = resolverWorkForce(cellNumber + 1, nextBoard);
                    if (finish)
                    {
                        return(board : finishedBoard, finish : finish, resolved : resolved);
                    }
                }

                // console.log(`resolverWorkForce: xxxxxxxxxxxxxxxxxxxxxxxxx !!! no possible value dead end: cell:${cellNumber}`, board)
                // all cell values are wrong
                return(board : null, finish : false, resolved : false);
            }
        }
Exemplo n.º 36
0
 public static void Solve(SudokuBoard board)
 {
     SudokuSolver.Solve(board, 0);
 }
Exemplo n.º 37
0
        public IActionResult Sudoku()
        {
            var board = new SudokuBoard();

            return(View(board.Board));
        }
Exemplo n.º 38
0
        public void Test_VerifyBoard()
        {
            try

            {
                SudokuBoard board = new SudokuBoard();
                //Test valid board
                board.Board = new int[9, 9] {
                    { 4, 3, 5, 2, 6, 9, 7, 8, 1 },
                    { 6, 8, 2, 5, 7, 1, 4, 9, 3 },
                    { 1, 9, 7, 8, 3, 4, 5, 6, 2 },
                    { 8, 2, 6, 1, 9, 5, 3, 4, 7 },
                    { 3, 7, 4, 6, 8, 2, 9, 1, 5 },
                    { 9, 5, 1, 7, 4, 3, 6, 2, 8 },
                    { 5, 1, 9, 3, 2, 6, 8, 7, 4 },
                    { 2, 4, 8, 9, 5, 7, 1, 3, 6 },
                    { 7, 6, 3, 4, 1, 8, 2, 5, 9 }
                };
                if (!board.VerifyBoard())
                {
                    Assert.Fail("Valid board tested but failed VerifyBoard()");
                }

                //Test board with empty elements
                board.Board = new int[9, 9] {
                    { 4, 3, 5, 2, 6, 9, 7, 8, 1 },
                    { 6, 8, 2, 5, 7, 1, 4, 9, 3 },
                    { 1, 9, 0, 8, 3, 4, 0, 6, 2 },
                    { 8, 2, 6, 1, 0, 5, 3, 4, 7 },
                    { 3, 7, 4, 6, 8, 2, 0, 1, 5 },
                    { 9, 0, 1, 7, 4, 3, 6, 2, 8 },
                    { 5, 1, 9, 3, 2, 6, 8, 7, 4 },
                    { 2, 4, 8, 0, 5, 7, 1, 3, 6 },
                    { 7, 6, 3, 4, 1, 8, 2, 5, 9 }
                };

                if (board.VerifyBoard())
                {
                    Assert.Fail("Board with missing elements passed VerifyBoard()");
                }

                //Test board that has invalid elements
                board.Board = new int[9, 9] {
                    { 4, 3, 5, 2, 6, 9, 7, 8, 1 },
                    { 6, 8, 2, 5, 7, 1, 4, 9, 3 },
                    { 9, 9, 7, 8, 3, 4, 5, 6, 2 },
                    { 8, 2, 6, 1, 9, 5, 3, 4, 7 },
                    { 3, 7, 4, 6, 8, 2, 9, 9, 5 },
                    { 9, 5, 1, 7, 4, 3, 6, 2, 8 },
                    { 5, 1, 9, 3, 2, 6, 8, 7, 4 },
                    { 2, 4, 8, 9, 5, 9, 1, 3, 6 },
                    { 7, 6, 3, 4, 1, 8, 2, 5, 9 }
                };


                if (board.VerifyBoard())
                {
                    Assert.Fail("Invalid complete board passed VerifyBoard()");
                }
            }
            catch (Exception e)
            {
                Assert.Fail("Test_VerifyBoard threw an exception. " + e.Message);
            }
        }