public long Solve() { var text = File.ReadAllLines(@"..\..\Problems\Problem096.txt"); var sudokus = new List<Sudoku>(); var addSudoku = new Sudoku(); var row = 0; foreach (var line in text) { if (line.Contains("Grid")) { addSudoku = new Sudoku(); row = 0; continue; } addSudoku.AddRow(row, line); row++; if (row == 9) { sudokus.Add(addSudoku); } } var sum = 0; foreach (var sudoku in sudokus) { sum = sum + sudoku.FirtThree(); } return sum; }
public static void Main() { //string file = "Sudoku.in"; //string[] lines = File.ReadAllLines(file); string[] lines = ReadLinesFromConsole(); Sudoku s = new Sudoku(lines); // 0 = free // - = turn off // + = turn on int i = 0; int j = 0; int k = 0; while (s.Steps < 81) { if (s.Fixed[i, j] || s.TurnOff(i, j, k)) { if (j < 8) { j++; } else { i++; j = 0; } k = 0; } else { do { if (k < 8) { k++; break; } else { if (j > 0) { j--; } else { i--; j = 8; } k = s.Solution[i, j] - 1; if (!s.TurnOn(i, j, k)) { k = 8; } } } while (true); } } s.PrintSolution(); }
public void impossible() { var sudoku = new Sudoku(new SudokuLegalMoveVerifier()); var problemParser = new SudokuProblemParser(); var problemGrid = problemParser.parseProblem(SudokuExamples.NOT_SOLVABLE_PROBLEM); var actualSolution = sudoku.solve(problemGrid); Assert.IsNull(actualSolution); }
public Game(int fieldSize, Sudoku.Controller game) { this.game = game; this.fieldSize = fieldSize; intField = new List<string>(); //field = new TextBox[fieldSize, fieldSize]; //intField = new short[fieldSize, fieldSize]; listField = new List<Models.Square>(); }
private void check(String problem, String solution) { var sudoku = new Sudoku(new SudokuLegalMoveVerifier()); var problemParser = new SudokuProblemParser(); var solutionGrid = problemParser.parseProblem(solution); var problemGrid = problemParser.parseProblem(problem); var actualSolution = sudoku.solve(problemGrid); var prettyPrinter = new SudokuPrettyPrinter(); Assert.That(prettyPrinter.prettyPrint(actualSolution) , Is.EqualTo(prettyPrinter.prettyPrint(solutionGrid) )); }
public void SetupBoard(Sudoku.ViewModels.MainViewModel viewModel) { if (viewModel == null) throw new ArgumentNullException("viewModel"); var board = viewModel.Board; if (board == null) throw new ArgumentNullException("board"); SetupGrid(board); SetupTextboxes(viewModel); }
public static void Sudoku_Standart_9x9() { Sudoku sudoku = new Sudoku(); sudoku.LoadXml(Alist.Xml.Transform.FileToElement("standart_9x9.xml")); sudoku.BlockType.Add(new BlockType()); sudoku.Initialize(); LousySudoku.Generator generator = new LousySudoku.Generator(sudoku, 2000, 1); generator.Generate(); if (!sudoku.IsCompleted()) Assert.Fail("Didn't generate sudoku"); else Debug.Print.Sudoku2D(sudoku); sudoku.Clear(); //for (int k = 0; ; k++) //{ // bool success = true; // for (int i = 0; (i < sudoku.Block.Count) && success; i++) // { // success = sudoku.Block[i].Generate(); // } // if (success) // success = sudoku.IsCompleted(); // if (success) // { // Console.WriteLine("Success"); // Debug.Print.Sudoku2D(sudoku); // return; // } // else // { // sudoku.Clear(); // } // if ((k > 0) && (k % 10000 == 0)) // { // Assert.Inconclusive("To much attempts to build sudoku"); // } //} }
public static void PrintSimple(Sudoku sudoku) { for (int row = 0; row < 9; row++) { if (row % 3 == 0) Console.WriteLine("+---+---+---+"); for (int col = 0; col < 9; col++) { if (col % 3 == 0) Console.Write('|'); SudokuValues cellVal = sudoku[new SudokuPosition(col, row)]; if (cellVal == SudokuValues.All) Console.Write(' '); else if (cellVal.Count == 1) Console.Write(cellVal.First() + 1); else Console.Write('?'); } Console.WriteLine("|"); } Console.WriteLine("+---+---+---+"); }
public static Sudoku LoadSudoku(string filename) { Sudoku sudoku = new Sudoku(); using (StreamReader sr = new StreamReader(filename, Encoding.ASCII)) { for (int row = 0; row < 9; row++) { string[] vals = sr.ReadLine().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (vals.Length == 0 || vals[0][0] == '#') { row--; continue; } for (int col = 0; col < 9; col++) { SudokuValues val = vals[col] == "*" ? SudokuValues.All : new SudokuValues(new byte[] { (byte)(Byte.Parse(vals[col], CultureInfo.InvariantCulture) - 1) }); sudoku[new SudokuPosition(col, row)] = val; } } } return sudoku; }
public void ClearPuzzle() { sudokuInstance = null; _sudokuView.ClearPuzzle(); CreateLayout(); }
public static void Main(string[] args) { System.Diagnostics.Stopwatch testTime = new System.Diagnostics.Stopwatch(); testTime.Start(); LousySudoku.UnitTest.Common.Run(5); testTime.Stop(); Console.WriteLine("Time elapsed: {0}", testTime.Elapsed); Console.ReadKey(); return; int size = 9; List<Number> number = new List<Number> { }; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { number.Add (new Number(NumberType.Empty, new Position(i, j))); } } //Debug.Print.Position(new Position(17, 5)); //Debug.Print.Number(number); List<BlockType> blockType = new List<BlockType> { }; BlockType standart = new BlockType(); //standart.SetChecker(LousySudoku.Method.CheckMethod_Standart); //standart.SetGenerator // (LousySudoku.Method.GenerateMethod_Standart); blockType.Add(standart); List<Block> block = new List<Block> { }; Sudoku sudoku = new Sudoku(blockType, block, number, size); for (int col = 0; col < size; col++) { block.Add(new Block( sudoku, standart, number.FindAll(x => x.Coordinate.GetCoordinate(0) == col) )); block.Add(new Block( sudoku, standart, number.FindAll(x => x.Coordinate.GetCoordinate(1) == col) )); } for (int i = 0; i < size; i += 3) { for (int l = 0; l < size; l += 3) { Block b = new Block(sudoku, standart); for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { b.AddChild(sudoku.GetNumber( new Position(i + j, k + l))); } } block.Add(b); } } //sudoku.Block.ForEach(new Action<Block>(Debug.Print.Block)); Alist.Xml.Transform.ElementToFile (sudoku.UnloadXml(), "standart_12x12.xml"); //LousySudoku.Constant.rand = new Random(); //foreach (Number numb in sudoku.Number) //{ // Console.Write("{0}; ", numb.parent.Count); //} //Console.WriteLine(); //sudoku.Block.ForEach(x => Console.Write("{0}, ", x.Child.Count)); Generator g = new Generator(sudoku, 1000000, 1); System.Diagnostics.Stopwatch s0 = new System.Diagnostics.Stopwatch(); s0.Start(); Console.WriteLine(g.Generate()); s0.Stop(); Console.WriteLine(s0.Elapsed); Console.WriteLine(g.AttemptsRemain); Debug.Print.Sudoku2D(sudoku); sudoku.Clear(); //bool isContinue = true; //for (int i = 0; isContinue; i++) //{ // bool success = true; //Block generate //for (int j = 0; (j < sudoku.Block.Count) && (success); j++) //{ // success = sudoku.Block[j].Generate(); //} //Number generate // for (int j = 0; (j < sudoku.Number.Count) && success; j++) // { // success // = LousySudoku.Method.Generate(sudoku.Number[j]); //#if DEBUG // if (!success) // ; //#endif // } // //List<int> digit = new List<int> // // { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // //bool toDo = true; // //for (int k = 0; (k < 9) && toDo; k++) // //{ // // int index = rand.Next(digit.Count - 1); // // int newnumb = digit[index]; // // numb.Modify(newnumb); // // digit.Remove(newnumb); // // if (numb.IsBlockRight()) // // { // // toDo = false; // // } // //} // //if (toDo) // // success = false; // ///End of attempt // if (!sudoku.Block.All(x => x.IsRight())) // success = false; // //success = sudoku.IsRight(); // if (i % 1000 == 0) // { // Console.WriteLine("Attempt #{0}", i); // Debug.Print.Sudoku2D(sudoku); // //LousySudoku.Constant.rand = new Random(); // } // if (success) // { // Console.WriteLine("Stopped at {0}", i); // Debug.Print.Sudoku2D(sudoku); // isContinue = false; // } // else // { // //sudoku = new Sudoku(blockType, block, number, 9); // sudoku.Clear(); // } // } Debug.Common.ShowSudoku(sudoku, size); Console.ReadKey(); return; //Tmp; Console.Write("Enter secret code, to run debug. Or press enter: "); string s = Console.ReadLine(); if (s != "2713") { Run(); return; } //LousySudoku.Sudoku sudoku = Debug.TestSudoku1(); //Console.WriteLine("Change number"); //sudoku.ChangeNumber(new Position(2, 1), 9); //Console.WriteLine("Print sudoku"); //Debug.ShowSudoku(sudoku, 9); ///Debug.TryLoadDll(); //Console.ReadLine(); //Debug.TryLoadDll("Sudoku.dll"); //Console.ReadLine(); ///Debug.ShowSudoku(Debug.SudokuEventTest(Debug.GetStandart9(null)), 9); //Sudoku sudoku = Debug.GetStandart25(null); //(new Generator(sudoku, 10, 1)).Generate(); //Debug.ShowSudoku(sudoku, 25); ///Debug.TestGeneration(); Debug.Common.TestSudokuFiles(); Console.ReadLine(); }
static void Main(string[] args) { //Menu numéro 1 de choix de la grille à jouer Console.WriteLine("\n\n\n TP1 - Résolution de Sudoku par différentes méthodes\n"); Console.WriteLine("1. Grille Initiale"); Console.WriteLine("2. Grille Easy"); Console.WriteLine("3. Grille Hardest"); Console.WriteLine("4. Grille Top 95"); Console.WriteLine("5. Quitter la résolution de Sudoku"); Console.WriteLine("\n=> Entrez votre choix: "); int choix; //Test de conformité du choix try { choix = int.Parse(Console.ReadLine()); } catch (Exception e) { choix = -1; Console.WriteLine("\n\nSaisie invalide\n\n"); } //Initialisation du detecteur de grille int numSudo; switch (choix) { case 1: Console.WriteLine("Grille Initiale"); //Le detecteur prend un chiffre de 1 à 4 en fonction de la grille choisie numSudo = 1; //L'initialisation du Sudoku se lance en prenant en argument ce detecteur Sudoku(numSudo); break; case 2: Console.WriteLine("Grille Easy"); numSudo = 2; Sudoku(numSudo); break; case 3: Console.WriteLine("Grille Hardest"); numSudo = 3; Sudoku(numSudo); break; case 4: Console.WriteLine("Grille Top 95"); numSudo = 4; Sudoku(numSudo); break; case 5: Console.WriteLine("Vous avez choisi de quitter le programme."); Console.ReadLine(); break; } //Initialisation du Sudoku void Sudoku(int n) { //Initialisation des variables String text; int i, j; i = 0; j = 0; int k = 0; //Création de l'objet Sudoku en fonction du detecteur if (n == 1) { //Création d'une liste de 0 int[] grid = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Noyau.Sudoku recup = new Noyau.Sudoku(grid); Console.WriteLine(recup.ToString()); //Envoi de l'objet dans le solveur Sudoku_Solver(1, recup); } if (n == 2) { Noyau.Sudoku recup = new Sudoku(); text = getLine("Sudoku_Easy50.txt", -1); char[] b = new char[text.Length]; using (StringReader sr = new StringReader(text)) { while (k != 81) { if (j == 9) { i++; j = 0; } sr.Read(b, 0, 1); recup.SetCell(i, j, Int32.Parse(b)); j++; k++; } } Console.WriteLine(recup.ToString()); Sudoku_Solver(2, recup); } if (n == 3) { Noyau.Sudoku recup = new Sudoku(); text = getLine("Sudoku_hardest.txt", -1); char[] b = new char[text.Length]; using (StringReader sr = new StringReader(text)) { while (k != 81) { if (j == 9) { i++; j = 0; } sr.Read(b, 0, 1); recup.SetCell(i, j, Int32.Parse(b)); j++; k++; } } Sudoku_Solver(3, recup); } if (n == 4) { Noyau.Sudoku recup = new Sudoku(); text = getLine("Sudoku_top95.txt", -1); char[] b = new char[text.Length]; using (StringReader sr = new StringReader(text)) { while (k != 81) { if (j == 9) { i++; j = 0; } sr.Read(b, 0, 1); recup.SetCell(i, j, Int32.Parse(b)); j++; k++; } } Sudoku_Solver(4, recup); } } void Sudoku_Solver(int n, Sudoku s) { //Menu numéro 2 du choix de la méthode de resolution Console.WriteLine("\nChoisissez parmis les différentes méthodes à disposition: \n\n"); Console.WriteLine(" 1. Algorithme génétique"); Console.WriteLine(" 2. SMT OR-Tools"); Console.WriteLine(" 3. CSP "); Console.WriteLine(" 4. SMT Z3 "); Console.WriteLine(" 5. Liens dansants "); Console.WriteLine(" 6. Norvig "); Console.WriteLine(" 7. Réseaux de neurones "); Console.WriteLine("\n\n\n"); //Declaration du chronometre Stopwatch stopwatch = new Stopwatch(); //Declaration de la fitness var fitness = new SudokuFitness(s); int solution; try { solution = int.Parse(Console.ReadLine()); } catch (Exception e) { solution = -1; Console.WriteLine("\n\n Saisie invalide\n\n"); } Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.WriteLine(" Grille choisie :"); Console.WriteLine("\n"); //Print de la grille choisie Console.WriteLine(s.ToString()); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); switch (solution) { case 1: Console.WriteLine("Résolution du Sudoku par Algorithme génétique"); SolverGeneticSharp sgs = new SolverGeneticSharp(); //Demarrage du chronometre stopwatch.Start(); s = sgs.ResoudreSudoku(s); //Arrete du chronometre stopwatch.Stop(); Console.WriteLine(s.ToString()); //Evaluation de la fitness : si fitness = 0 alors le Sudoku est résolu parfaitement Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); //Temps d'execution Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; case 2: Console.WriteLine("\n"); Console.WriteLine("Résolution du Sudoku par SMT ORTools"); Solveur_tools ots = new Solveur_tools(); stopwatch.Start(); s = ots.ResoudreSudoku(s); stopwatch.Stop(); Console.WriteLine(s.ToString()); Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; case 3: Console.WriteLine("Résolution du Sudoku par CSP "); //CSP csp = new CSP(); stopwatch.Start(); //s = csp.ResoudreSudoku(s); stopwatch.Stop(); Console.WriteLine(s.ToString()); Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; case 4: Console.WriteLine("Résolution du Sudoku par SMT Z3 "); //SMT smt = new SMT(); stopwatch.Start(); //s = smt.ResoudreSudoku(s); stopwatch.Stop(); Console.WriteLine(s.ToString()); Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; case 5: Console.WriteLine("Résolution du Sudoku par LiensDansants "); SolveurLD dancing = new SolveurLD(); stopwatch.Start(); s = dancing.ResoudreSudoku(s); stopwatch.Stop(); Console.WriteLine(s.ToString()); Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; case 6: Console.WriteLine("Résolution du Sudoku par Norvig "); Norvig norvig = new Norvig(); stopwatch.Start(); s = norvig.ResoudreSudoku(s); stopwatch.Stop(); Console.WriteLine(s.ToString()); Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; case 7: Console.WriteLine(" Résolution du Sudoku par réseau de neurones convolués "); //Neurones neur = new Neurones(); stopwatch.Start(); //s = neur.ResoudreSudoku(s); stopwatch.Stop(); Console.WriteLine(s.ToString()); Console.WriteLine("Fitness : "); Console.WriteLine(fitness.Evaluate(s)); Console.WriteLine("Durée d'exécution: {0} secondes", stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); Console.WriteLine("\n"); Console.WriteLine("******************************************************"); Console.WriteLine("\n"); Console.ReadLine(); break; } } string getLine(string fileName, int index) //Récupère un String Sudoku d'un fichier { String[] lines = getFile(fileName); if (index < 0 || index >= lines.Length) { Random rnd = new Random(); index = rnd.Next(lines.Length); } return(lines[index]); } string[] getFile(string fileName) //Récupère tout les Sudokus d'un fichier et les stocks dans une liste { DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory); String path = Path.Combine(myDirectory.Parent.Parent.Parent.FullName, fileName); String[] lines = File.ReadAllLines(path); return(lines); } }
public ProgramGrp6() { Sudoku = new Sudoku(); Name = "Grp 6 CSP"; }
public GameRecord(Sudoku sudoku) { DateCompleted = DateTime.Now; Difficulty = sudoku.difficulty; TimeString = sudoku.TimeString; }
///////////////////////////////////////////////////////////////////////////////// /// <summary> /// Handles the KeyDown event. /// </summary> /// <param name="e"></param> /// protected override void OnKeyDown(KeyEventArgs e) { string tempMessage = null; switch (e.KeyCode) { case Keys.Down: ++CurrentRow; e.Handled = true; break; case Keys.Up: --CurrentRow; e.Handled = true; break; case Keys.Right: ++CurrentColumn; e.Handled = true; break; case Keys.Left: --CurrentColumn; e.Handled = true; break; case Keys.Delete: case Keys.Space: case Keys.Back: // // Clear cell // if (!Locked[CurrentRow, CurrentColumn]) { Matrix[CurrentRow, CurrentColumn] = 0; } e.Handled = true; break; case Keys.X: // // Lock/Unlock cell // Locked[CurrentRow, CurrentColumn] = !Locked[CurrentRow, CurrentColumn]; e.Handled = true; break; case Keys.Q: case Keys.Escape: // // Quit form // Close(); e.Handled = true; break; case Keys.C: // // Clear the puzzle // tempMessage = "Contents cleared..."; Matrix = new Sudoku(); SetupLockedCells(); e.Handled = true; break; case Keys.I: // // Initialize the puzzle with AI Escargot // LoadAiEscargot(); tempMessage = InfoMessage; e.Handled = true; break; case Keys.D0: case Keys.D1: case Keys.D2: case Keys.D3: case Keys.D4: case Keys.D5: case Keys.D6: case Keys.D7: case Keys.D8: case Keys.D9: // // Change cell contents // if (!Locked[CurrentRow, CurrentColumn]) { Matrix[CurrentRow, CurrentColumn] = e.KeyCode - Keys.D0; } e.Handled = true; break; case Keys.S: // // Try to solve the puzzle // if (Matrix.Consistent) { Stopwatch sw = new Stopwatch(); sw.Start(); bool solved = Matrix.Solve(); sw.Stop(); if (!solved) { tempMessage = "Puzzle does not have a solution..."; MessageBox.Show("Puzzle does not have a solution!", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { double ms = (double)sw.ElapsedTicks * 1e3 / (double)Stopwatch.Frequency; if (ms < 1) // very fast { tempMessage = string.Format("Solved in {0:N0} ns", ms * 1e3); } else { tempMessage = string.Format("Solved in {0:N0} ms", ms); } } } e.Handled = true; break; } // Keep row/column in valid bounds // CurrentColumn = Math.Max(0, Math.Min(Matrix.ColumnCount - 1, CurrentColumn)); CurrentRow = Math.Max(0, Math.Min(Matrix.RowCount - 1, CurrentRow)); UpdateStatus(tempMessage); base.OnKeyDown(e); }
public ProgramGrp4() { sudoku = new Sudoku(); Console.WriteLine(" Non implémanté"); }
public void GenerateRandomSolution() { var sudoku = new Sudoku(rnd: new Random()); Assert.AreEqual(SudokuState.Solved, sudoku.GetState()); }
// POST: api/Sudoku public int Post([FromBody] Sudoku sudoku) { return(sudokuDAL.Add(sudoku)); }
public async Task <ActionResult> IsValid(Sudoku sudoku) { var result = await this.sudokuService.IsValid(sudoku); return(Json(result)); }
private static void PrintSudoku(Sudoku sudoku) { for (int row = 0; row < 9; row++) { if (row % 3 == 0) Console.WriteLine("*************************************"); else Console.WriteLine("*---+---+---*---+---+---*---+---+---*"); for (int part = 0; part < 9; part += 3) { for (int col = 0; col < 9; col++) { Console.Write(col % 3 == 0 ? '*' : '|'); PrintFieldPart(sudoku[new SudokuPosition(col, row)], part); } Console.WriteLine('*'); } } Console.WriteLine("*************************************"); }
private SudokuSolver(Sudoku data) { Data = data; Techniques = Technique.GetTechniques(this); }
public SudokuFitness(Sudoku targetSudoku) { _targetSudoku = targetSudoku; }
private void SetupTextboxes(Sudoku.ViewModels.MainViewModel viewModel) { Board board = viewModel.Board; var rangeRule = new ValidationRules.BoardRange(board); for (int row = 1; row <= board.Size; row++) { var gridRow = row + (row / board.SquareSize) - (row % board.SquareSize == 0 ? 1 : 0); for (int column = 1; column <= board.Size; column++) { var gridColumn = column + (column / board.SquareSize) - (column % board.SquareSize == 0 ? 1 : 0); var textbox = new TextBox { Height = 40, Width = 40, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, FontSize = 20 }; Grid.SetColumn(textbox, gridColumn); Grid.SetRow(textbox, gridRow); AssignShortcut(textbox, row, column); var cell = board[row, column]; textbox.DataContext = cell; textbox.PreviewLostKeyboardFocus += (sender, e) => { var tb = sender as TextBox; int value; if (!string.IsNullOrEmpty(tb.Text) && !(int.TryParse(tb.Text, out value) && cell.IsValid(value))) e.Handled = true; else tb.ToolTip = null; }; textbox.IsEnabled = cell.Enabled; if (!cell.Enabled) textbox.Foreground = disbleBrush; Children.Add(textbox); var textbinding = new Binding { Mode = BindingMode.TwoWay, Path = new PropertyPath("Value"), TargetNullValue = string.Empty, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, //ValidatesOnDataErrors = true, //NotifyOnValidationError = true, NotifyOnTargetUpdated = true, UpdateSourceExceptionFilter = (expression, exception) => { viewModel.Notify(exception.Message); textbox.ToolTip = exception.Message; return expression; } }; textbinding.ValidationRules.Add(rangeRule); textbox.SetBinding(TextBox.TextProperty, textbinding); } } AssignShortcutsToWindow(); }
public static void DoOnCompleted(Sudoku sudoku) { completed = true; }
protected override void Act() { _sudoku = new Sudoku(SudokuFileMother.XmlContent); }
public void Solve2Test() { var sudoku = new Sudoku(); sudoku.SetCellValue(0, 0, 1); sudoku.SetCellValue(0, 5, 8); sudoku.SetCellValue(0, 6, 4); sudoku.SetCellValue(1, 1, 2); sudoku.SetCellValue(1, 5, 4); sudoku.SetCellValue(1, 6, 9); sudoku.SetCellValue(2, 0, 9); sudoku.SetCellValue(2, 2, 3); sudoku.SetCellValue(2, 3, 2); sudoku.SetCellValue(2, 4, 5); sudoku.SetCellValue(2, 5, 6); sudoku.SetCellValue(3, 0, 6); sudoku.SetCellValue(3, 6, 5); sudoku.SetCellValue(3, 7, 7); sudoku.SetCellValue(3, 8, 1); sudoku.SetCellValue(4, 0, 4); sudoku.SetCellValue(4, 1, 1); sudoku.SetCellValue(4, 3, 8); sudoku.SetCellValue(4, 5, 5); sudoku.SetCellValue(4, 7, 6); sudoku.SetCellValue(4, 8, 2); sudoku.SetCellValue(5, 0, 5); sudoku.SetCellValue(5, 1, 3); sudoku.SetCellValue(5, 2, 2); sudoku.SetCellValue(5, 8, 4); sudoku.SetCellValue(6, 3, 5); sudoku.SetCellValue(6, 4, 8); sudoku.SetCellValue(6, 5, 2); sudoku.SetCellValue(6, 6, 7); sudoku.SetCellValue(6, 8, 9); sudoku.SetCellValue(7, 2, 1); sudoku.SetCellValue(7, 3, 3); sudoku.SetCellValue(7, 7, 4); sudoku.SetCellValue(8, 2, 8); sudoku.SetCellValue(8, 3, 1); sudoku.SetCellValue(8, 8, 5); sudoku.SetCellValue(8, 8, 5); var puzzle = @"100008400 020004900 903256000 600000571 410805062 532000004 000582709 001300040 008100005 ".Replace(" ", ""); Assert.AreEqual(puzzle, sudoku.ToString()); var solver = new SudokuSolver(sudoku); solver.Solve(); var solution = @"175938426 826714953 943256187 689423571 417895362 532671894 364582719 751369248 298147635 ".Replace(" ", ""); Assert.AreEqual(solution, sudoku.ToString()); Assert.IsTrue(sudoku.IsSolved()); }
public static void SudokuEventTestSubscriber2(Sudoku sudoku) { Console.WriteLine("{0} congrats, completed", 0); }
public void sudoku_grid_checks_validity() { var input = new[] { "4;1,4,2,3,2,3,1,4,4,2,3,1,3,1,4,2", "4;2,1,3,2,3,2,1,4,1,4,2,3,2,3,4,1" }; var expected = new[] {"True", "False"}; var results = new Sudoku(input).Run(); AssertExtensions.AreEqual(expected, results); }
public void UpdateSudoku(Sudoku dbSudoku, SudokuModel sudoku) { dbSudoku.SudokuArray = sudoku.Sudoku; dbSudoku.SudokuId = sudoku.SudokuId; dbSudoku.SudokuDate = sudoku.Date; }
public Sudoku Post([FromBody] Sudoku sudoku) { sudoku.board = Sudoku.Solve(sudoku.board); return(sudoku); }
public void Setup() { sudoku = Generator.Generate(Difficulty, 5); }
public void Solve() { // Creates the model. CpModel model = new CpModel(); // Creates the variables. int num_vals = 9; //Creat the Sudoku grid IntVar[][] grid = new IntVar[9][]; for (int k = 0; k < 9; k++) { grid[k] = new IntVar[9]; } //get initial sudoku grid and put the 9 possibilities in Empty cells for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (Sudoku.getCaseInitialSudoku(i, j) == 0) { grid[i][j] = model.NewIntVar(1, num_vals, "C" + i.ToString() + j.ToString()); } else { grid[i][j] = model.NewIntVar(Sudoku.getCaseInitialSudoku(i, j), Sudoku.getCaseInitialSudoku(i, j), "C" + i.ToString() + j.ToString()); } } } // Adds a different constraint. for (int k = 0; k < 9; k++) { //All the ligne might have a different number in each cells model.AddAllDifferent(GetRow(grid, k)); //All the columns might have a different number in each cells model.AddAllDifferent(GetColumn(grid, k)); } //All 9 Regions might have a different number in each cells for (int region = 0; region < 9; region++) { model.AddAllDifferent(GetRegion(grid, region)); } // Creates a solver and solves the model. CpSolver solver = new CpSolver(); VarArraySolutionPrinter cb = new VarArraySolutionPrinter(grid); solver.SearchAllSolutions(model, cb); int[][] values = cb.getValues(); Sudoku.setSudoku(values); }
public StatisticWindow(Sudoku vm) { InitializeComponent(); this.DataContext = vm; // Set the data context for this window }
public Sudoku Solve(Sudoku s) { //Working parameters : Pop = 5000 , ite = 100 return(Eval(s, 5000, 0, 100)); }
public static string PrintBlocks(Sudoku sudoku) { string result = "Printing.. "; for (int i = 0; i < sudoku.Block.Count; i++) { result += "\n" + "#" + i.ToString() + " " + BlockToString(sudoku.Block[i]); } return result; }
private void CreateLayout() { sudokuInstance = new Sudoku(); _hasStartedPuzzle = false; _sudokuView.RenderPuzzle(); }
public static void ShowSudoku(Sudoku sudoku, int size) { Console.WriteLine(" - - - - - - - AL"); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Console.Write("{0:00} ", sudoku.GetNumber(new Position(i, j)).Value); } Console.WriteLine(); } Console.WriteLine(" / / / / / / AL"); }
public ActionResult Solve(Sudoku board) { return(View("Result", "Home", board)); }
public static void ShowSudokuRightness(Sudoku sudoku, int size) { Console.WriteLine(" - - - - - - - AL"); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Console.Write("{0} ", (sudoku.GetNumber(new Position(i, j)).IsRight()) ? 1 : 0); } Console.WriteLine(); } Console.WriteLine(" / / / / / / AL"); }
/// <summary> /// Constructor with a mask sudoku to solve, assuming a length of 9 genes /// </summary> /// <param name="targetSudoku">the target sudoku to solve</param> public SudokuPermutationsChromosome(Sudoku targetSudoku) : this(targetSudoku, 9) { }
public static string SudokuCoordinates(Sudoku sudoku) { string result = ""; for (int i = 0; i < sudoku.Block.Count; i++) { result += String.Format("Block #{0} : {1} \n", i, BlockCoordinates(sudoku.Block[i])); } return result; }
public void Sudoku_ValidateSolutionTest() { testCases.ToList().ForEach(_ => Assert.AreEqual(_.Expected, Sudoku.ValidateSolution(_.Board))); }
public static Sudoku SudokuEventTest(Sudoku sudoku) { Generator generator = new Generator(sudoku, fillness: 1); generator.Generate(); sudoku.onCompleted += SudokuEventTestSubscriber1; sudoku.onFilled += SudokuEventTestSubscriber2; sudoku.SetNumber(new Position(0, 0), sudoku.GetNumber(new Position(0, 0)).Value); return sudoku; }
public static void Main() { bool closeRequested = false; while (!closeRequested) { NewPuzzle: Console.Clear(); int?[,] generatedBoard = Sudoku.Generate(); int?[,] activeBoard = (int?[, ])generatedBoard.Clone(); int x = 0; int y = 0; Console.Clear(); while (!closeRequested && ContainsNulls(activeBoard)) { Console.SetCursorPosition(0, 0); Console.WriteLine("Sudoku"); Console.WriteLine(); ConsoleWrite(activeBoard, generatedBoard); Console.WriteLine(); Console.WriteLine("Press arrow keys to select a cell."); Console.WriteLine("Press 1-9 to insert values."); Console.WriteLine("Press [delete] or [backspace] to remove."); Console.WriteLine("Press [escape] to exit."); Console.WriteLine("Press [end] to generate a new sudoku."); Console.SetCursorPosition(y * 2 + 2 + (y / 3 * 2), x + 3 + +(x / 3)); switch (Console.ReadKey(true).Key) { case ConsoleKey.UpArrow: x = x <= 0 ? 8 : x - 1; break; case ConsoleKey.DownArrow: x = x >= 8 ? 0 : x + 1; break; case ConsoleKey.LeftArrow: y = y <= 0 ? 8 : y - 1; break; case ConsoleKey.RightArrow: y = y >= 8 ? 0 : y + 1; break; case ConsoleKey.D1: case ConsoleKey.NumPad1: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 1, x, y) ? 1 : activeBoard[x, y]; break; case ConsoleKey.D2: case ConsoleKey.NumPad2: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 2, x, y) ? 2 : activeBoard[x, y]; break; case ConsoleKey.D3: case ConsoleKey.NumPad3: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 3, x, y) ? 3 : activeBoard[x, y]; break; case ConsoleKey.D4: case ConsoleKey.NumPad4: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 4, x, y) ? 4 : activeBoard[x, y]; break; case ConsoleKey.D5: case ConsoleKey.NumPad5: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 5, x, y) ? 5 : activeBoard[x, y]; break; case ConsoleKey.D6: case ConsoleKey.NumPad6: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 6, x, y) ? 6 : activeBoard[x, y]; break; case ConsoleKey.D7: case ConsoleKey.NumPad7: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 7, x, y) ? 7 : activeBoard[x, y]; break; case ConsoleKey.D8: case ConsoleKey.NumPad8: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 8, x, y) ? 8 : activeBoard[x, y]; break; case ConsoleKey.D9: case ConsoleKey.NumPad9: activeBoard[x, y] = IsValidMove(activeBoard, generatedBoard, 9, x, y) ? 9 : activeBoard[x, y]; break; case ConsoleKey.End: goto NewPuzzle; case ConsoleKey.Backspace: case ConsoleKey.Delete: activeBoard[x, y] = generatedBoard[x, y] ?? null; break; case ConsoleKey.Escape: closeRequested = true; break; } } if (!closeRequested) { Console.Clear(); Console.WriteLine("Sudoku"); Console.WriteLine(); ConsoleWrite(activeBoard, generatedBoard); Console.WriteLine(); Console.WriteLine("You Win!"); Console.WriteLine(); Console.WriteLine("Play Again [enter], or quit [escape]?"); GetInput: switch (Console.ReadKey(true).Key) { case ConsoleKey.Enter: break; case ConsoleKey.Escape: closeRequested = true; Console.Clear(); break; default: goto GetInput; } } } Console.Clear(); Console.Write("Sudoku was closed."); }
public static void Main(string[] args) { System.Diagnostics.Stopwatch testTime = new System.Diagnostics.Stopwatch(); testTime.Start(); LousySudoku.UnitTest.Common.Run(5); testTime.Stop(); Console.WriteLine("Time elapsed: {0}", testTime.Elapsed); Console.ReadKey(); return; int size = 9; List <Number> number = new List <Number> { }; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { number.Add (new Number(NumberType.Empty, new Position(i, j))); } } //Debug.Print.Position(new Position(17, 5)); //Debug.Print.Number(number); List <BlockType> blockType = new List <BlockType> { }; BlockType standart = new BlockType(); //standart.SetChecker(LousySudoku.Method.CheckMethod_Standart); //standart.SetGenerator // (LousySudoku.Method.GenerateMethod_Standart); blockType.Add(standart); List <Block> block = new List <Block> { }; Sudoku sudoku = new Sudoku(blockType, block, number, size); for (int col = 0; col < size; col++) { block.Add(new Block( sudoku, standart, number.FindAll(x => x.Coordinate.GetCoordinate(0) == col) )); block.Add(new Block( sudoku, standart, number.FindAll(x => x.Coordinate.GetCoordinate(1) == col) )); } for (int i = 0; i < size; i += 3) { for (int l = 0; l < size; l += 3) { Block b = new Block(sudoku, standart); for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { b.AddChild(sudoku.GetNumber( new Position(i + j, k + l))); } } block.Add(b); } } //sudoku.Block.ForEach(new Action<Block>(Debug.Print.Block)); Alist.Xml.Transform.ElementToFile (sudoku.UnloadXml(), "standart_12x12.xml"); //LousySudoku.Constant.rand = new Random(); //foreach (Number numb in sudoku.Number) //{ // Console.Write("{0}; ", numb.parent.Count); //} //Console.WriteLine(); //sudoku.Block.ForEach(x => Console.Write("{0}, ", x.Child.Count)); Generator g = new Generator(sudoku, 1000000, 1); System.Diagnostics.Stopwatch s0 = new System.Diagnostics.Stopwatch(); s0.Start(); Console.WriteLine(g.Generate()); s0.Stop(); Console.WriteLine(s0.Elapsed); Console.WriteLine(g.AttemptsRemain); Debug.Print.Sudoku2D(sudoku); sudoku.Clear(); //bool isContinue = true; //for (int i = 0; isContinue; i++) //{ // bool success = true; //Block generate //for (int j = 0; (j < sudoku.Block.Count) && (success); j++) //{ // success = sudoku.Block[j].Generate(); //} //Number generate // for (int j = 0; (j < sudoku.Number.Count) && success; j++) // { // success // = LousySudoku.Method.Generate(sudoku.Number[j]); //#if DEBUG // if (!success) // ; //#endif // } // //List<int> digit = new List<int> // // { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // //bool toDo = true; // //for (int k = 0; (k < 9) && toDo; k++) // //{ // // int index = rand.Next(digit.Count - 1); // // int newnumb = digit[index]; // // numb.Modify(newnumb); // // digit.Remove(newnumb); // // if (numb.IsBlockRight()) // // { // // toDo = false; // // } // //} // //if (toDo) // // success = false; // ///End of attempt // if (!sudoku.Block.All(x => x.IsRight())) // success = false; // //success = sudoku.IsRight(); // if (i % 1000 == 0) // { // Console.WriteLine("Attempt #{0}", i); // Debug.Print.Sudoku2D(sudoku); // //LousySudoku.Constant.rand = new Random(); // } // if (success) // { // Console.WriteLine("Stopped at {0}", i); // Debug.Print.Sudoku2D(sudoku); // isContinue = false; // } // else // { // //sudoku = new Sudoku(blockType, block, number, 9); // sudoku.Clear(); // } // } Debug.Common.ShowSudoku(sudoku, size); Console.ReadKey(); return; //Tmp; Console.Write("Enter secret code, to run debug. Or press enter: "); string s = Console.ReadLine(); if (s != "2713") { Run(); return; } //LousySudoku.Sudoku sudoku = Debug.TestSudoku1(); //Console.WriteLine("Change number"); //sudoku.ChangeNumber(new Position(2, 1), 9); //Console.WriteLine("Print sudoku"); //Debug.ShowSudoku(sudoku, 9); ///Debug.TryLoadDll(); //Console.ReadLine(); //Debug.TryLoadDll("Sudoku.dll"); //Console.ReadLine(); ///Debug.ShowSudoku(Debug.SudokuEventTest(Debug.GetStandart9(null)), 9); //Sudoku sudoku = Debug.GetStandart25(null); //(new Generator(sudoku, 10, 1)).Generate(); //Debug.ShowSudoku(sudoku, 25); ///Debug.TestGeneration(); Debug.Common.TestSudokuFiles(); Console.ReadLine(); }
public static void TestGeneration() { int[,] numbs = new int[25, 25]; for (int i = 0; i < 25; i++) for (int j = 0; j < 25; j++) numbs[i, j] = 0; Sudoku sudoku9 = GetStandart9(numbs); Stopwatch time9 = new Stopwatch(); Generator generator9 = new Generator(sudoku9, fillness: 1); Console.WriteLine(generator9.AttemptsRemain); time9.Start(); Console.WriteLine(generator9.Generate()); time9.Stop(); ShowSudoku(sudoku9, 9); System.Xml.Linq.XElement Sudoku = sudoku9.UnloadXml(); Console.WriteLine(Sudoku); Sudoku sudoku0 = new Sudoku(); //(null, null, null, null, 0); sudoku0.LoadXml(Sudoku); Console.WriteLine("Go"); ShowSudoku(sudoku0, 9); PrintBlocks(sudoku0); Sudoku sudoku16 = GetStandart16(numbs); Stopwatch time16 = new Stopwatch(); Generator generator16 = new Generator(sudoku16, attemptsNumber: 0, fillness: 1); ///sudoku16.MixNumbers(); //Console.WriteLine("Sudoku. Разбор полетов и template: \n {0}", SudokuCoordinates(sudoku16)); Console.WriteLine(generator16.AttemptsRemain); time16.Start(); Console.WriteLine(generator16.Generate()); time16.Stop(); ShowSudoku(sudoku16, 16); Console.WriteLine("\n \n {0}x9x{2} against {1}x16x{3}", time9.Elapsed, time16.Elapsed, generator9.AttemptsRemain, generator16.AttemptsRemain); }
public ProgramGrp4() { Sudoku = new Sudoku(); Name = "Grp4 Dancing Links"; s.sudoku = Sudoku; }
public static Sudoku TestSudoku1() { Console.WriteLine("Starting TestSudoku1()"); int[,] value = new int[9, 9]; ////////////// Random rand = new Random(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { value[i, j] = rand.Next(9); } } //////////////// NumberType[,] mask = new NumberType[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { mask[i, j] = NumberType.Modify; } } Position[][] block = new Position[9][]; for (int i = 0; i < 9; i++) { block[i] = new Position[9]; } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { block[i][j] = new Position(i, j); } } Console.WriteLine("temp vars initialized"); Console.WriteLine("Call constructor Sufoku"); Sudoku sudoku = new Sudoku(); //(new Position(9, 9), value, mask, block, 9); Console.WriteLine("Call method Debug.ShowSudoku"); ShowSudoku(sudoku, 9); Console.WriteLine("Return sudoku. Method TestSudoku1() ends here"); return sudoku; }
public Sudoku ResoudreSudoku(Sudoku s) { CpModel model = new CpModel(); IntVar[][] tab_s = new IntVar[9][]; for (int i = 0; i < tab_s.Length; i++) { tab_s[i] = new IntVar[9]; } for (int i = 0; i < tab_s.Length; i++) { for (int j = 0; j < tab_s[i].Length; j++) { tab_s[i][j] = model.NewIntVar(1, 9, "grid" + "(" + i + "," + j + ")"); } } //constraints all differents on rows for (int i = 0; i < tab_s.Length; i++) { model.AddAllDifferent(tab_s[i]); } // Constraints all differents on colums IntVar[] tpm = new IntVar[9]; for (int j = 0; j < tab_s[0].Length; j++) { for (int i = 0; i < tab_s.Length; i++) { tpm[i] = tab_s[i][j]; } model.AddAllDifferent(tpm); Array.Clear(tpm, 0, tpm.Length); } // Constraint all differents on cells List <IntVar> ls = new List <IntVar>(); for (int i = 0; i < 7; i += 3) { for (int j = 0; j < 7; j += 3) { for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { ls.Add(tab_s[i + k][j + l]); } } model.AddAllDifferent(ls); ls.Clear(); } } //initial Value for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (s.GetCell(i, j) != 0) { model.Add(tab_s[i][j] == s.GetCell(i, j)); } } } //creation of the Solver CpSolver solver = new CpSolver(); CpSolverStatus status = solver.Solve(model); List <int> lsol = new List <int>(); if (status == CpSolverStatus.Feasible) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { lsol.Add((int)(solver.Value(tab_s[i][j]))); } } } Sudoku resolution = new Sudoku(lsol); return(resolution); }
public void Test(string expected, int[][] board) => Assert.AreEqual(expected, Sudoku.DoneOrNot(board));
public Sudoku Solve(Sudoku s) { //Création d'une instance Contexte using (Context ctx = new Context(new Dictionary <string, string>() { { "model", "true" } })) { // 9x9 matrix of integer variables IntExpr[][] X = new IntExpr[9][]; for (uint i = 0; i < 9; i++) // uint : entier positif { X[i] = new IntExpr[9]; //Liste de 9 case for (uint j = 0; j < 9; j++) //Parcourt la liste //pour chaque case on affecte une valeur { X[i][j] = (IntExpr)ctx.MkConst(ctx.MkSymbol("x_" + (i + 1) + "_" + (j + 1)), ctx.IntSort); } } // each cell contains a value in {1, ..., 9} Expr[][] cells_c = new Expr[9][]; for (uint i = 0; i < 9; i++) { cells_c[i] = new BoolExpr[9]; for (uint j = 0; j < 9; j++) { cells_c[i][j] = ctx.MkAnd(ctx.MkLe(ctx.MkInt(1), X[i][j]), ctx.MkLe(X[i][j], ctx.MkInt(9))); } } // each row contains a digit at most once BoolExpr[] rows_c = new BoolExpr[9]; for (uint i = 0; i < 9; i++) { rows_c[i] = ctx.MkDistinct(X[i]); } // each column contains a digit at most once BoolExpr[] cols_c = new BoolExpr[9]; for (uint j = 0; j < 9; j++) { IntExpr[] column = new IntExpr[9]; for (uint i = 0; i < 9; i++) { column[i] = X[i][j]; } cols_c[j] = ctx.MkDistinct(column); } // each 3x3 square contains a digit at most once BoolExpr[][] sq_c = new BoolExpr[3][]; for (uint i0 = 0; i0 < 3; i0++) { sq_c[i0] = new BoolExpr[3]; for (uint j0 = 0; j0 < 3; j0++) { IntExpr[] square = new IntExpr[9]; for (uint i = 0; i < 3; i++) { for (uint j = 0; j < 3; j++) { square[3 * i + j] = X[3 * i0 + i][3 * j0 + j]; } } sq_c[i0][j0] = ctx.MkDistinct(square); //compare chaque carré } } BoolExpr sudoku_c = ctx.MkTrue(); foreach (BoolExpr[] t in cells_c) { sudoku_c = ctx.MkAnd(ctx.MkAnd(t), sudoku_c); } sudoku_c = ctx.MkAnd(ctx.MkAnd(rows_c), sudoku_c); sudoku_c = ctx.MkAnd(ctx.MkAnd(cols_c), sudoku_c); foreach (BoolExpr[] t in sq_c) { sudoku_c = ctx.MkAnd(ctx.MkAnd(t), sudoku_c); } // sudoku instance, we use '0' for empty cells var listCell = new List <List <int> >(); for (int i = 0; i < 9; i++) { listCell.Add(new List <int>()); for (int j = 0; j < 9; j++) { listCell[listCell.Count - 1].Add(s.Cells[(9 * i) + j]); // mettre j à la place du 1 non ? } } int[,] instance = To2D(listCell.Select(ligne => ligne.ToArray()).ToArray()); BoolExpr instance_c = ctx.MkTrue(); for (uint i = 0; i < 9; i++) { for (uint j = 0; j < 9; j++) { instance_c = ctx.MkAnd(instance_c, (BoolExpr) ctx.MkITE(ctx.MkEq(ctx.MkInt(instance[i, j]), ctx.MkInt(0)), ctx.MkTrue(), ctx.MkEq(X[i][j], ctx.MkInt(instance[i, j])))); } } Solver solve = ctx.MkSolver(); solve.Assert(sudoku_c); solve.Assert(instance_c); if (solve.Check() == Status.SATISFIABLE) { Model m = solve.Model; Expr[,] R = new Expr[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { R[i, j] = m.Evaluate(X[i][j]); } } Console.WriteLine("Sudoku solution:"); var solu = new Sudoku(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { //Console.Write(" " + R[i, j]); solu.Cells[i * 9 + j] = int.Parse(R[i, j].ToString()); } Console.WriteLine(); } return(solu); } else { Console.WriteLine("Failed to solve sudoku"); } return(null); } }
public static void Sudoku2D(Sudoku sudoku) { Position size = sudoku.Size; for (int i = 0; i <= size.GetCoordinate(0); i++) { Console.WriteLine(); for (int j = 0; j <= size.GetCoordinate(1); j++) { Console.Write( "{0} - ", sudoku.GetNumber(new Position(i, j)).Value); } } }
public void AddRecord(Sudoku sudoku) { GameRecords.Add(new GameRecord(sudoku)); }