private static IImmutableList <Tuple <int, int, int, bool> > BuildInternalRowsForSudoku(Core.Sudoku s)
        {
            var rowsByCols =
                from row in Rows
                from col in Cols
                let value = s.GetCell(row, col)
                            select BuildInternalRowsForCell(row, col, value);

            return(rowsByCols.SelectMany(cols => cols).ToImmutableList());
        }
Esempio n. 2
0
        // Fonction principale pour construire le CSP à partir d'un masque de Sudoku à résoudre
        public static CSP GetSudokuCSP(Core.Sudoku s)
        {
            //initialisation à l'aide des contraintes communes

            var toReturn = GetSudokuBaseCSP();


            // Ajout des contraintes spécifiques au masque fourni

            //var sArray = s.getInitialSudoku();
            var cellVars = toReturn.getVariables();


            //récupération du masque
            var mask = new Dictionary <int, int>();

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    var cellVal = s.GetCell(i, j);
                    if (cellVal != 0)
                    {
                        mask[i * 9 + j] = cellVal;
                    }
                }
            }

            //Ajout des contraintes de masque en faisant défiler les variables existantes

            var maskQueue = new Queue <int>(mask.Keys);

            var currentMaskIdx = maskQueue.Dequeue();
            var currentVarName = GetVarName(currentMaskIdx / 9, currentMaskIdx % 9);

            foreach (Variable objVar in cellVars.toArray())
            {
                if (objVar.getName() == currentVarName)
                {
                    //toReturn.addConstraint(new ValueConstraint(objVar, mask[currentMaskIdx]));
                    var cellValue = mask[currentMaskIdx];
                    toReturn.setDomain(objVar, new Domain(new object[] { cellValue }));
                    if (maskQueue.Count == 0)
                    {
                        break;
                    }
                    currentMaskIdx = maskQueue.Dequeue();
                    currentVarName = GetVarName(currentMaskIdx / 9, currentMaskIdx % 9);
                }
            }

            return(toReturn);
        }
Esempio n. 3
0
        private IList <IList <IList <int> > > GetRowsPermutationsUncached(Core.Sudoku objSudoku)
        {
            var toReturn = new List <IList <IList <int> > >(9);

            for (int i = 0; i < 9; i++)
            {
                var tempList = new List <IList <int> >();
                foreach (var perm in AllPermutations)
                {
                    // Permutation should match current mask row numbers, and have numbers different that other mask rows
                    if (!Range9.Any(rowIdx => Range9.Any(j => objSudoku.GetCell(rowIdx, j) > 0 &&
                                                         ((rowIdx == i && perm[j] != objSudoku.GetCell(rowIdx, j)) || (rowIdx != i && perm[j] == objSudoku.GetCell(rowIdx, j))))))
                    {
                        tempList.Add(perm);
                    }
                }
                toReturn.Add(tempList);
            }

            return(toReturn);
        }
        public static CombinatorialSudoku Convert(Core.Sudoku sudoku)
        {
            var problem = new[, ]
            {
                { 0, 0, 7, 0, 0, 2, 9, 3, 0 },
                { 0, 8, 1, 0, 0, 0, 0, 0, 5 },
                { 9, 0, 4, 7, 0, 0, 1, 6, 0 },
                { 0, 1, 0, 8, 0, 0, 0, 0, 6 },
                { 8, 4, 6, 0, 0, 0, 5, 9, 2 },
                { 5, 0, 0, 0, 0, 6, 0, 1, 0 },
                { 0, 9, 2, 0, 0, 8, 3, 0, 1 },
                { 4, 0, 0, 0, 0, 0, 6, 5, 0 },
                { 0, 6, 5, 4, 0, 0, 2, 0, 0 }
            };

            for (int row = 1; row <= 9; row++)
            {
                for (int column = 1; column <= 9; column++)
                {
                    problem[row - 1, column - 1] = sudoku.GetCell(row - 1, column - 1);
                }
            }
            return(new CombinatorialSudoku(problem));
        }
Esempio n. 5
0
        public static (BaseModel model, double accuracy) TrainAndTest(BaseModel model)
        {
            // Global parameters
            string datasetPath = @"Sudoku.NeuralNetwork\Dataset\sudoku.csv.gz";
            int    numSudokus  = 1000;

            // ML parameters
            double testPercent  = 0.2;
            float  learningRate = .001F;
            int    batchSize    = 32;
            int    epochs       = 2;

            Console.WriteLine("Initialize dataset");
            var(sPuzzles, sSols) = DataSetHelper.ParseCSV(datasetPath, numSudokus);
            var(_sPuzzzlesTrain, _sPuzzlesTest) = DataSetHelper.SplitDataSet(sPuzzles, testPercent);
            var(_sSolsTrain, _sSolsTest)        = DataSetHelper.SplitDataSet(sSols, testPercent);

            Console.WriteLine("Preprocess data");
            var sPuzzzlesTrain = DataSetHelper.PreprocessSudokus(_sPuzzzlesTrain);
            var sSolsTrain     = DataSetHelper.PreprocessSudokus(_sSolsTrain);
            var sPuzzlesTest   = DataSetHelper.PreprocessSudokus(_sPuzzlesTest);
            var sSolsTest      = DataSetHelper.PreprocessSudokus(_sSolsTest);

            // Add optimizer
            var adam = new Keras.Optimizers.Adam(learningRate);

            model.Compile(loss: "sparse_categorical_crossentropy", optimizer: adam);

            Console.WriteLine("Train model");
            model.Fit(sPuzzzlesTrain, sSolsTrain, batch_size: batchSize, epochs: epochs);

            // Test model
            int correct = 0;

            for (int i = 0; i < 1; i++)
            {
                Console.WriteLine("Testing " + i);

                // Predict result
                var prediction = Solve(sPuzzlesTest[i], model);

                // Convert to sudoku
                var sPredict = new Core.Sudoku()
                {
                    Cells = prediction.flatten().astype(np.int32).GetData <int>().ToList()
                };
                var sSol = new Core.Sudoku()
                {
                    Cells = ((sSolsTest[i] + 0.5) * 9).flatten().astype(np.int32).GetData <int>().ToList()
                };

                // Compare sudoku
                var same = true;
                for (int j = 0; j < 9; j++)
                {
                    for (int k = 0; k < 9; k++)
                    {
                        if (sPredict.GetCell(j, k) != sSol.GetCell(j, k))
                        {
                            same = false;
                        }
                    }
                }
                Console.WriteLine("Prediction : \n" + sPredict);
                Console.WriteLine("Solution : \n" + sSol);

                if (same)
                {
                    correct += 1;
                }
            }

            // Calculate accuracy
            var accuracy = (correct / sPuzzlesTest.size) * 100;

            // Return
            return(model, accuracy);
        }