public void assign(GrilleSudoku s, int cell, int value, List <int> assignment, List <List <int> > possibilites, List <List <int> > pruned)
        {
            assignment.Add(cell);
            s.SetCell(cell / 9, cell % 9, value);

            if (possibilites[cell].Contains(value))
            {
                possibilites[cell].Remove(value);
            }

            if (!pruned[cell].Contains(value))
            {
                pruned[cell].Add(value);
            }

            if (possibilites[cell].Count == 0)
            {
                possibilites[cell].Add(10);
            }

            // supp la Valeur des Possibilités des Voisins de la Cellule
            foreach (int neighboor_value in Cell_Neighboor(s, cell))
            {
                if (possibilites[neighboor_value].Contains(value))
                {
                    possibilites[neighboor_value].Remove(value);
                }
                if (!pruned[neighboor_value].Contains(value))
                {
                    pruned[neighboor_value].Add(value);
                }
            }
        }
        public void Solve(GrilleSudoku s)
        {
            Console.WriteLine("Begin solving Sudoku");
            Console.WriteLine("The problem is: ");

            int[][] problem = new int[9][];
            for (int row = 0; row <= 8; row++)
            {
                problem[row] = new int[9];
                for (int column = 0; column <= 8; column++)
                {
                    problem[row][column] = s.GetCellule(row, column);
                }
            }

            int[,] tab = new int[9, 9];
            for (int row = 0; row <= 8; row++)
            {
                problem[row] = new int[9];
                for (int column = 0; column <= 8; column++)
                {
                    tab[row, column] = s.GetCellule(row, column);
                }
            }
            //DisplayMatrix(problem);
            int numOrganisms = 200;
            int maxEpochs    = 5000;
            int maxRestarts  = 20;

            Sudoku sudo = Sudoku.New(tab);
            Sudoku soln = Solvette(sudo, numOrganisms, maxEpochs, maxRestarts);

            Console.WriteLine("Best solution found: ");

            //DisplayMatrix(soln);

            //affichage du sudoku
            Console.WriteLine(soln.ToString());
            //Reconversion depuis int[,]
            for (int row = 0; row < 9; row++)
            {
                for (int column = 0; column < 9; column++)
                {
                    s.Cellules[row * 9 + column] = soln.CellValues[row, column];
                }
            }

            int err = Error(soln);

            if (err == 0)
            {
                Console.WriteLine("Success \n");
            }
            else
            {
                Console.WriteLine("Did not find optimal solution \n");
            }
            Console.WriteLine("End Sudoku demo");
            Console.ReadLine();
        }
        public void AC3(GrilleSudoku s, List <List <int> > possibilites)
        {
            bool test = true;
            int  CaseCheck;

            while (test)
            {
                test = false;
                for (int i = 0; i < 81; i++)
                {
                    if (possibilites[i].Count == 1 && possibilites[i][0] != 10)
                    {
                        test = true;
                    }
                }
                if (test == true)
                {
                    CaseCheck = getNextMRV(possibilites);

                    //AC3 ETAPE : 1
                    //Nb Possibilites = 1
                    if (possibilites[CaseCheck].Count == 1)
                    {
                        s.SetCell(CaseCheck / 9, CaseCheck % 9, possibilites[CaseCheck][0]);
                        DeletePossibilites(s, possibilites, CaseCheck, possibilites[CaseCheck][0]);
                    }
                }
            }
        }
Пример #4
0
        void ISudokuSolver.Solve(GrilleSudoku s)
        {
            var suudokuResolu = this.Solve(s);

            Enumerable.Range(0, 81).ToList().ForEach(i => s.Cellules[i] = suudokuResolu.Cellules[i]);
            //throw new NotImplementedException();
        }
Пример #5
0
        public bool Resolve(GrilleSudoku s)            // La fonction solve va pemettre de choisir la solution valide satsifaisant les contraintes de sodoku
        {
            for (int ligne = 0; ligne < Size; ligne++) // parcourt les lignes
            {
                for (int col = 0; col < Size; col++)   // parcourt les colonnes
                {
                    // Ce double for parcourt chaque colonne pour une ligne donnée
                    if (s.GetCellule(ligne, col) == 0)           // empty: si la cellule est vide alors on va rentrer dans la boucle for
                    {
                        for (int value = 1; value <= 9; value++) // qui va tester les valeur de 1 à 9
                        {
                            if (IsValid(s, ligne, col, value))   // Si la valeur est valide avec les conditions de validité qu'on va définirapres dans le code
                            {
                                s.SetCell(ligne, col, value);    // Alors on remplie la case vide avec la valeur valide

                                if (Resolve(s))                  // Et on appelle la fonction elle-meme pour la récursivité : Principe de backtracking
                                {
                                    return(true);                // On on valide la solution
                                }
                                else
                                {
                                    s.SetCell(ligne, col, 0);  // Sinon on réinitialise la valeur à 0
                                }
                            }
                        }

                        return(false); // On refait le même processus
                    }
                }
            }

            return(true); // Jusqu'à ce qu'on trouve une solution valide et on la garde
        }
        public void Solve(GrilleSudoku s)
        {
            List <List <int> > list_cell = new List <List <int> >();

            foreach (var i in System.Linq.Enumerable.Range(0, 9))
            {
                var ligne = new List <int>(9);
                list_cell.Add(ligne);
                foreach (var j in System.Linq.Enumerable.Range(0, 9))
                {
                    ligne.Add(s.GetCellule(j, i));
                }
            }
            var monTableau = list_cell.Select(l => l.ToArray()).ToArray();
            var monPuzzle  = new Puzzle(monTableau, false);
            var monSolver  = new Solver(monPuzzle);

            monSolver.DoWork(this, new System.ComponentModel.DoWorkEventArgs(null));

            foreach (var i in System.Linq.Enumerable.Range(0, 9))
            {
                foreach (var j in System.Linq.Enumerable.Range(0, 9))
                {
                    s.SetCell(i, j, monPuzzle.Rows[i][j].Value);
                }
            }
        }
Пример #7
0
 private bool IsValid(GrilleSudoku s, int ligne, int col, int value)
 //appel les trois fonctions
 {
     return(IsLigneValid(s, ligne, value) &&
            IsCarreValid(s, ligne, col, value) &&
            IsColValid(s, col, value));
 }
        public virtual void SolveSudoku(GrilleSudoku s)
        {
            Dirichlet[] dirArray = Enumerable.Repeat(Dirichlet.Uniform(CellDomain.Count), CellIndices.Count).ToArray();

            //On affecte les valeurs fournies par le masque à résoudre en affectant les distributions de probabilités initiales
            foreach (var cellIndex in GrilleSudoku.IndicesCellules)
            {
                if (s.Cellules[cellIndex] > 0)
                {
                    //Vector v = Vector.Zero(CellDomain.Count);
                    //v[s.Cellules[cellIndex] - 1] = 1.0;


                    //Todo: Alternative: le fait de mettre une proba non nulle permet d'éviter l'erreur "zero probability" du Sudoku Easy-n°2, mais le Easy#3 n'est plus résolu
                    //tentative de changer la probabilite pour solver le sudoku 3 infructueuse
                    Vector v = Vector.Constant(CellDomain.Count, EpsilonProba);
                    v[s.Cellules[cellIndex] - 1] = FixedValueProba;

                    dirArray[cellIndex] = Dirichlet.PointMass(v);
                }
            }

            CellsPrior.ObservedValue = dirArray;


            // Todo: tester en inférant sur d'autres variables aléatoire,
            // et/ou en ayant une approche itérative: On conserve uniquement les cellules dont les valeurs ont les meilleures probabilités
            //et on réinjecte ces valeurs dans CellsPrior comme c'est également fait dans le projet neural nets.
            //

            // IFunction draw_categorical(n)// where n is the number of samples to draw from the categorical distribution
            // {
            //
            // r = 1

            /* for (i=0; i<9; i++)
             *          for (j=0; j<9; j++)
             *                  for (k=0; k<9; k++)
             *                          ps[i][j][k] = probs[i][j][k].p; */


            //DistributionRefArray<Discrete, int> cellsPosterior = (DistributionRefArray<Discrete, int>)InferenceEngine.Infer(Cells);
            //var cellValues = cellsPosterior.Point.Select(i => i + 1).ToList();

            //Autre possibilité de variable d'inférence (bis)
            Dirichlet[] cellsProbsPosterior = InferenceEngine.Infer <Dirichlet[]>(ProbCells);

            foreach (var cellIndex in GrilleSudoku.IndicesCellules)
            {
                if (s.Cellules[cellIndex] == 0)
                {
                    //s.Cellules[cellIndex] = cellValues[cellIndex];


                    var mode  = cellsProbsPosterior[cellIndex].GetMode();
                    var value = mode.IndexOf(mode.Max()) + 1;
                    s.Cellules[cellIndex] = value;
                }
            }
        }
Пример #9
0
 // Méthode qui est appelé au start du script Jeu afin d'initialiser les objets
 public void Init()
 {
     tileReference = GameObject.Find("TilePrefab");
     grille        = GameObject.Find("Jeu").GetComponent <Jeu>().getGrille();
     colonne       = grille.getCols();
     ligne         = grille.getRows();
     generateNumberSelection();
 }
Пример #10
0
        public void Solve(GrilleSudoku s)
        {
            int[][] sJaggedTableau = Enumerable.Range(0, 9).Select(i => Enumerable.Range(0, 9).Select(j => s.GetCellule(i, j)).ToArray()).ToArray();
            var     sTableau       = To2D(sJaggedTableau);

            Program.estValide(sTableau, 0);
            Enumerable.Range(0, 9).ToList().ForEach(i => Enumerable.Range(0, 9).ToList().ForEach(j => s.SetCell(i, j, sTableau[i, j])));
        }
Пример #11
0
 /// <summary>
 /// Constructor that accepts a Sudoku to solve
 /// </summary>
 /// <param name="targetCore.Sudoku">the target sudoku to solve</param>
 public SudokuCellsChromosome(GrilleSudoku targetSudoku) : base(81)
 {
     _targetSudoku = targetSudoku;
     for (int i = 0; i < Length; i++)
     {
         ReplaceGene(i, GenerateGene(i));
     }
 }
Пример #12
0
 public void IterationSetup()
 {
     IterationPuzzles = new List <Core.GrilleSudoku>(NbPuzzles);
     for (int i = 0; i < NbPuzzles; i++)
     {
         IterationPuzzles.Add(AllPuzzles[Difficulty][i].CloneSudoku());
     }
     SolverPresenter.Solver.Solve(GrilleSudoku.Parse("483921657967345001001806400008102900700000008006708200002609500800203009005010300"));
 }
Пример #13
0
 /// <summary>
 /// Constructor with a mask and a number of genes
 /// </summary>
 /// <param name="targetCore.Sudoku">the target sudoku to solve</param>
 /// <param name="length">the number of genes</param>
 public SudokuPermutationsChromosome(GrilleSudoku targetSudoku, int length) : base(length)
 {
     TargetSudoku           = targetSudoku;
     TargetRowsPermutations = GetRowsPermutations(TargetSudoku);
     for (int i = 0; i < Length; i++)
     {
         ReplaceGene(i, GenerateGene(i));
     }
 }
Пример #14
0
 public void Solve(GrilleSudoku s)
 {
     // SolveWithSubstitutions(s);
     //  SolveWithScope(s);
     //  SolveWithAsumptions(s);
     // SolveOriginalVersion(s);
     SolveOriginalCleanup(s);
     //  z3Context.MkTactic("smt");
 }
Пример #15
0
    private GameObject infos;               // Référence à l'object Infos pour afficher dans son élément texte les informations de la partie

    void Start()
    {
        grille = new GrilleSudoku(9, 9); // Définition de la grille de 9 par 9
        grille.initVal(0);               // Toutes les cases sont à 0
        GameObject diffManager = GameObject.Find("DifficultyManager");

        if (diffManager) // Vérification que la scène SudokuMenu a fait son travail
        {
            if (diffManager.GetComponent <sceneManager>().resumeGame)
            {
                // Cas où l'on veut reprendre la partie du fichier sauvegardeSudoku
                var loadedData = JSON.Parse(File.ReadAllText(defineSudoku.cheminSauvegarde));
                numGrille      = loadedData["num"].ToString();
                difficulte     = loadedData["difficulte"];
                temps          = float.Parse(loadedData["timer"]);
                affichageTemps = loadedData["timerString"];
                grille.chargementGrilleSauvegarde();
                Destroy(diffManager);
            }
            else
            {
                difficulte = diffManager.GetComponent <sceneManager>().difficulty; // Récupération de la difficulté choisit dans la scène SudokuMenu
                Destroy(diffManager);

                //Choix d'un niveau au hasard selon la difficulté précedement choisie
                int    cpt           = 0;
                string directoryPath = defineSudoku.getCheminDifficulte(difficulte);
                var    info          = new DirectoryInfo(directoryPath);
                var    fileInfo      = info.GetFiles();
                foreach (FileInfo f in fileInfo)
                {
                    if (f.Extension == ".json")
                    {
                        cpt++;
                    }
                }
                int level = UnityEngine.Random.Range(1, cpt + 1);
                numGrille = level.ToString();
            }
        }
        else // Afin de pouvoir lancer la scène Sudoku sans problème
        {
            string[] level = SelectionNiveauAleatoire(); // Chaine de caractères avec la difficulté et le numéro de grille
            difficulte = level[0];
            numGrille  = level[1]; // Numéro de grille choisit au hasard
        }
        infos = GameObject.Find("Infos");
        infos.GetComponent <TextMeshProUGUI>().text = "Difficulty : " + difficulte + "           Level : " + numGrille + "\nTimer : " + affichageTemps; // Changement du texte des infos
        grille.chargementGrille(numGrille, difficulte);                                                                                                 // Chargement de la grille avec la difficulté et son numéro de grille
        UIManager = GameObject.Find("Jeu").GetComponent <UIManager>();
        UIManager.Init();                                                                                                                               // Initialisation des objets visuels
        parent = GameObject.Find("GridManager").transform;
        UIManager.GenerateGrid(0f, 0f, parent);                                                                                                         // Génération de la grille sur la scène
        grille.sauvegardeGrille();                                                                                                                      // Sauvegarde de la grille dès le lancement
    }
Пример #16
0
        private bool IsColValid(GrilleSudoku s, int col, int value)
        {
            for (var ligne = 0; ligne < Size; ligne++)
            {
                if (s.GetCellule(ligne, col) == value)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #17
0
        private bool IsLigneValid(GrilleSudoku s, int ligne, int value)
        {
            for (var col = 0; col < Size; col++)
            {
                if (s.GetCellule(ligne, col) == value)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #18
0
        /// <summary>
        /// Evaluates a single Sudoku board by counting the duplicates in rows, boxes
        /// and the digits differing from the target mask.
        /// </summary>
        /// <param name="testSudoku">the board to evaluate</param>
        /// <returns>the number of mistakes the Sudoku contains.</returns>
        public double Evaluate(GrilleSudoku testSudoku)
        {
            // We use a large lambda expression to count duplicates in rows, columns and boxes
            var cells  = testSudoku.Cellules.Select((c, i) => new { index = i, cell = c }).ToList();
            var toTest = cells.GroupBy(x => x.index / 9).Select(g => g.Select(c => c.cell))                                       // rows
                         .Concat(cells.GroupBy(x => x.index % 9).Select(g => g.Select(c => c.cell)))                              //columns
                         .Concat(cells.GroupBy(x => x.index / 27 * 27 + x.index % 9 / 3 * 3).Select(g => g.Select(c => c.cell))); //boxes
            var toReturn = -toTest.Sum(test => test.GroupBy(x => x).Select(g => g.Count() - 1).Sum());                            // Summing over duplicates

            toReturn -= cells.Count(x => _targetSudoku.Cellules[x.index] > 0 && _targetSudoku.Cellules[x.index] != x.cell);       // Mask
            return(toReturn);
        }
        // FONCTION POUR  BACKTRACKING
        public int Nombre_de_conflits(GrilleSudoku s, int cellule, int valeur, List <List <int> > possibilites)
        {
            int count = 0;

            foreach (int cell in Cell_Neighboor(s, cellule))
            {
                if (possibilites[cell].Count > 1 && possibilites[cell].Contains(valeur))
                {
                    count = count + 1;
                }
            }
            return(count);
        }
Пример #20
0
        /// <summary>
        /// builds a single Sudoku from the given row permutation genes
        /// </summary>
        /// <returns>a list with the single Sudoku built from the genes</returns>
        public virtual IList <GrilleSudoku> GetSudokus()
        {
            var listInt = new List <int>(81);

            for (int i = 0; i < 9; i++)
            {
                var perm = GetPermutation(i);
                listInt.AddRange(perm);
            }
            var sudoku = new GrilleSudoku(listInt);

            return(new List <GrilleSudoku>(new[] { sudoku }));
        }
Пример #21
0
 static void AddDataConstraints(GrilleSudoku data, Model model, Decision[][] grid)
 {
     for (int r = 0; r < 9; ++r)
     {
         for (int c = 0; c < 9; ++c)
         {
             if (data.GetCellule(r, c) != 0)
             {
                 model.AddConstraint("v" + r + c, grid[r][c] == data.GetCellule(r, c));
             }
         }
     }
 }
 public int[][] ConvertToMatrix(GrilleSudoku grille)  // conversion de grillesudoku en int[][]
 {
     int[][] sud = new int[9][];
     for (int i = 0; i < 9; i++)
     {
         sud[i] = new int[9];
         for (int j = 0; j < 9; j++)
         {
             sud[i][j] = grille.GetCellule(i, j);
         }
     }
     return(sud);
 }
Пример #23
0
        private bool IsColValid(GrilleSudoku s, int col, int value)
        //Vérifie que chaque nombre n'apparait qu'une fois sur la colonne
        {
            for (var ligne = 0; ligne < Size; ligne++)
            {
                if (s.GetCellule(ligne, col) == value)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #24
0
        private bool IsLigneValid(GrilleSudoku s, int ligne, int value)
        //Vérifie que chaque nombre n'apparait qu'une fois sur la ligne
        {
            for (var col = 0; col < Size; col++)
            {
                if (s.GetCellule(ligne, col) == value)
                {
                    return(false);
                }
            }

            return(true);
        }
        public bool Is_present(GrilleSudoku s, List <List <int> > possibilites, int poss, int position)
        {
            foreach (int voisin in Cell_Neighboor(s, position))
            {
                int ligne   = voisin / 9;
                int colonne = voisin % 9;

                if (s.GetCellule(ligne, colonne) == poss)
                {
                    return(false);
                }
            }
            return(true);
        }
 public void Solve(GrilleSudoku grid)
 {
     Sud      = new Sudoku(grid);
     s.sudoku = Sud;
     s.Solve();
     Sud = s.sudoku;
     for (int i = 0; i < 9; i++)
     {
         for (int j = 0; j < 9; j++)
         {
             grid.SetCell(i, j, Sud.getCaseSudoku(i, j));
         }
     }
 }
Пример #27
0
        public virtual void SolveSudoku(GrilleSudoku s)
        {
            Dirichlet[] dirArray = Enumerable.Repeat(Dirichlet.Uniform(CellDomain.Count), CellIndices.Count).ToArray();

            //On affecte les valeurs fournies par le masque à résoudre en affectant les distributions de probabilités initiales
            foreach (var cellIndex in GrilleSudoku.IndicesCellules)
            {
                if (s.Cellules[cellIndex] > 0)
                {
                    Vector v = Vector.Zero(CellDomain.Count);
                    v[s.Cellules[cellIndex] - 1] = 1.0;


                    //Todo: Alternative: le fait de mettre une proba non nulle permet d'éviter l'erreur "zero probability" du Sudoku Easy-n°2, mais le Easy#3 n'est plus résolu

                    //Vector v = Vector.Constant(CellDomain.Count, EpsilonProba);
                    //v[s.Cellules[cellIndex] - 1] = FixedValueProba;

                    dirArray[cellIndex] = Dirichlet.PointMass(v);
                }
            }

            CellsPrior.ObservedValue = dirArray;


            // Todo: tester en inférant sur d'autres variables aléatoire,
            // et/ou en ayant une approche itérative: On conserve uniquement les cellules dont les valeurs ont les meilleures probabilités et on réinjecte ces valeurs dans CellsPrior comme c'est également fait dans le projet neural nets.



            DistributionRefArray <Discrete, int> cellsPosterior = (DistributionRefArray <Discrete, int>)InferenceEngine.Infer(Cells);
            var cellValues = cellsPosterior.Point.Select(i => i + 1).ToList();

            //Autre possibilité de variable d'inférence (bis)
            //Dirichlet[] cellsProbsPosterior = InferenceEngine.Infer<Dirichlet[]>(ProbCells);

            foreach (var cellIndex in GrilleSudoku.IndicesCellules)
            {
                if (s.Cellules[cellIndex] == 0)
                {
                    s.Cellules[cellIndex] = cellValues[cellIndex];

                    //Autre possibilité de variable d'inférence (bis)
                    //var mode = cellsProbsPosterior[cellIndex].GetMode();
                    //var value = mode.IndexOf(1.0) + 1;
                    //s.Cellules[cellIndex] = value;
                }
            }
        }
        public void Solve(GrilleSudoku s)
        {
            string game = string.Concat(s.Cellules.Select(c => (c == 0) ? "." : c.ToString()));
            Dictionary <string, string> solution = LinqSudokuSolver.Search(LinqSudokuSolver.Parse_grid(game));

            for (int r = 0; r < cellIndices.Count(); r++)
            {
                for (int c = 0; c < cellIndices.Count(); c++)
                {
                    var cellules = Int32.Parse(solution[LinqSudokuSolver.Rows[r].ToString() + LinqSudokuSolver.Cols[c].ToString()]);

                    s.SetCell(r, c, cellules);
                }
            }
        }
        public void Solve(GrilleSudoku s)
        {
            var game     = String.Concat(s.Cellules.Select(c => (c == 0) ? "." : c.ToString()));
            var solution = LinqSudokuSolver.search(LinqSudokuSolver.parse_grid(game));

            foreach (var r in Enumerable.Range(0, 9))
            {
                foreach (var c in Enumerable.Range(0, 9))
                {
                    var cellules = Int32.Parse(solution[LinqSudokuSolver.rows[r].ToString() + LinqSudokuSolver.cols[c].ToString()]);

                    s.SetCell(r, c, cellules);
                }
            }
        }
        public void Solve(GrilleSudoku s)
        {
            //Création d'un solver Or-tools

            Solver solver = new Solver("Sudoku");

            //Création de la grille de variables

            IntVar[,] grid = solver.MakeIntVarMatrix(9, 9, 1, 9, "grid");
            IntVar[] grid_flat = grid.Flatten();



            //Masque de résolution
            foreach (int i in cellIndices)
            {
                foreach (int j in cellIndices)
                {
                    if (s.GetCellule(i, j) > 0)
                    {
                        solver.Add(grid[i, j] == s.GetCellule(i, j));
                    }
                }
            }

            //Un chiffre ne figure qu'une seule fois par ligne/colonne/cellule
            foreach (int i in cellIndices)
            {
                // Lignes
                solver.Add((from j in cellIndices
                            select grid[i, j]).ToArray().AllDifferent());

                // Colonnes
            }

            //Cellules



            //Début de la résolution
            DecisionBuilder db = solver.MakePhase(grid_flat,
                                                  Solver.INT_VAR_SIMPLE,
                                                  Solver.INT_VALUE_SIMPLE);

            solver.NewSearch(db);

            //Mise à jour du sudoku
        }