Ejemplo n.º 1
0
 public BaseSudokuAction(SolutionsTree a_tree, SudokuSolutionNode a_selected)
 {
     m_selected      = a_selected;
     m_tree_state    = new SolutionsTreeState(a_tree);
     m_tree          = a_tree;
     m_selected_tree = a_tree.SelectedSolutionNode;
 }
Ejemplo n.º 2
0
        private bool IsSolvable(SudokuSolutionNode a_node)
        {
            if (a_node.Board.IsSolved)
            {
                return(true);
            }

            if (!a_node.Board.IsSolvable)
            {
                return(false);
            }

            a_node.StepAll();

            SudokuSolutionNode node = a_node.Nodes.FirstOrDefault();

            if (node == null)
            {
                return(true);
            }

            node.StepAll();

            return(IsSolvable(node.Nodes.First()));
        }
        private void RefreshBoard()
        {
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                UndoRedoManager.Instance.Clear();

                SudokuSolutionNode selected_node = solutionsTree.SelectedSolutionNode;
                SudokuSolution     selected_sol  = solutionsCheckedListBox.SelectedSolution;

                foreach (TreeNode node in solutionsTree.Nodes)
                {
                    SudokuSolutionNode sol_node = solutionsTree.TreeNodeToSolutionNode(node);
                    if (sol_node.State == SudokuSolutionNodeState.Solution)
                    {
                        sol_node.Parent.RemoveNodes(sol_node);
                    }
                }

                SudokuSolutionNode last = solutionsTree.TreeNodeToSolutionNode(solutionsTree.Nodes.Cast <TreeNode>().Last());
                last.RemoveNodes();
                SudokuSolutionNode root = SudokuSolutionNode.CreateTree(solutionsTree.SelectedSolutionNode.Root);

                solutionsTree.UpdateTree(root, solutionsTree.SelectedSolutionNode);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 4
0
        private static void GenerateAllSolutionsTrees()
        {
            System.Console.WriteLine();
            System.Console.WriteLine("Generating all solutions trees...");
            System.Console.WriteLine();

            FileInfo[] files = new DirectoryInfo(Directories.Examples).GetFiles(FileExtensions.XmlZipMask);

            ShowProgress(0, 70);

            new DirectoryInfo(Directories.SolutionTrees).CreateOrEmpty();

            ConcurrentCounter counter = new ConcurrentCounter();

            Parallel.ForEach(files, (file) =>
            {
                SudokuBoard board = SudokuBoard.LoadFromFile(file.FullName);

                for (int i = 0; i < 4; i++)
                {
                    SudokuSolutionNode node = SudokuSolutionNode.CreateRoot(board);
                    node.SolveWithStepAll();
                    node.SaveToFile(Directories.SolutionTrees + Path.DirectorySeparatorChar +
                                    Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(file.FullName)) + "_rotate_" + i + FileExtensions.XmlZipExt);

                    board = board.Rotate();
                }

                counter.Increment();
                lock (counter)
                {
                    ShowProgress(counter.Value * 70 / files.Length, 70);
                }
            });
        }
Ejemplo n.º 5
0
        private IEnumerable <SudokuSolutionNode> RemoveIfExistsElsewhere(IEnumerable <SudokuSolutionNode> a_enum,
                                                                         SudokuSolutionNode a_node)
        {
            List <SudokuSolutionNode> list = new List <SudokuSolutionNode>(a_enum);

            foreach (SudokuSolutionNode node in a_node.Root.GetAllNodesEnumerator())
            {
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    if (list[i].Equals(node))
                    {
                        if (!Object.ReferenceEquals(list[i], node))
                        {
                            list.RemoveAt(i);
                        }
                    }
                }

                if (list.Count == 0)
                {
                    break;
                }
            }

            return(list);
        }
Ejemplo n.º 6
0
        public void Test_Solution_Tress_Verificator()
        {
            ProgressIndicator pi = new ProgressIndicator(System.Reflection.MethodBase.GetCurrentMethod().Name);

            FileInfo[] files = new DirectoryInfo(Directories.SolutionTrees).GetFiles(FileExtensions.XmlZipMask);

            string dir_diff = Directories.SolutionTrees + Path.DirectorySeparatorChar + "Verification_Failed";

            new DirectoryInfo(dir_diff).CreateOrEmpty();

            bool ok = true;

            ConcurrentCounter counter = new ConcurrentCounter();
            int index = 0;

            Parallel.ForEach(files, (file) =>
            {
                counter.Increment();
                pi.AddLine((counter.Value * 100 / files.Length).ToString());

                SudokuSolutionNode node = SudokuSolutionNode.LoadFromFile(file.FullName);

                foreach (SudokuSolutionNode n in node.GetAllNodesEnumerator())
                {
                    if (n.State == SudokuSolutionNodeState.Solution)
                    {
                        SudokuVerificator verificator = new SudokuVerificator(n.Board);

                        foreach (SudokuNumber number in n.Solution.Removed)
                        {
                            bool b = verificator.IsImpossible(number.Col, number.Row, number.Number - 1);

                            if (!b)
                            {
                                ok = false;

                                string diff_file = String.Format(
                                    "{0}{1}{2}_index_{3}_sol_type_{4}_coords_{5}_number_{6}{7}",
                                    dir_diff,
                                    Path.DirectorySeparatorChar,
                                    Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(file.FullName)),
                                    index,
                                    n.Solution.Type,
                                    number.Coords,
                                    number.Number,
                                    FileExtensions.XmlZipExt);

                                new SudokuIntermediateSolution(n.Parent.Board, n.Board,
                                                               n.Solution).SaveToFile(diff_file);

                                index++;
                            }
                        }
                    }
                }
            });

            Assert.IsTrue(ok);
        }
Ejemplo n.º 7
0
        public bool IsImpossible(int a_col, int a_row, int a_number_index)
        {
            SudokuBoard board = new SudokuBoard(m_board);

            board[a_col, a_row][a_number_index].State = SudokuNumberState.sudokucellstateSolved;
            SudokuSolutionNode node = SudokuSolutionNode.CreateRoot(board);

            return(!IsSolvable(node));
        }
Ejemplo n.º 8
0
        private TreeNode AddNextNode(TreeNode a_treeNode, SudokuSolutionNode a_solutionNode)
        {
            TreeNode node = null;

            node     = GetParentCollection(a_treeNode).Insert(GetParentCollection(a_treeNode).IndexOf(a_treeNode) + 1, a_solutionNode.Info);
            node.Tag = a_solutionNode;
            ColorNode(node);
            return(node);
        }
Ejemplo n.º 9
0
        public TreeNode SolutionNodeToTreeNode(SudokuSolutionNode a_node)
        {
            foreach (var node in Nodes.Cast <TreeNode>())
            {
                if (TreeNodeToSolutionNode(node).Equals(a_node))
                {
                    return(node);
                }
            }

            return(null);
        }
Ejemplo n.º 10
0
        private void ColorNode(TreeNode a_node)
        {
            SudokuSolutionNode node = TreeNodeToSolutionNode(a_node);

            if (node.State == SudokuSolutionNodeState.Solution)
            {
                if ((node.Solution.Type != SudokuSolutionType.MarkImpossibles) &&
                    (node.Solution.Type != SudokuSolutionType.MarkSolved) &&
                    (node.Solution.Type != SudokuSolutionType.SinglesInUnit))
                {
                    a_node.BackColor = Color.LightBlue;
                }
            }
        }
Ejemplo n.º 11
0
        public void Step(SudokuSolutionNode a_node)
        {
            if (a_node == null)
            {
                a_node = SelectedSolutionNode.Step();
                if (a_node == null)
                {
                    return;
                }
            }

            a_node.Parent.RemoveNodes(a_node);
            UpdateTree(a_node.Root, a_node);
        }
Ejemplo n.º 12
0
        public void Test_Unsolvable()
        {
            FileInfo[] files = new DirectoryInfo(Directories.TestExamples + Path.DirectorySeparatorChar +
                                                 "Unsolvable").GetFiles(FileExtensions.XmlZipMask);

            foreach (FileInfo file in files)
            {
                SudokuBoard board = SudokuBoard.LoadFromFile(file.FullName);
                Assert.IsNotNull(board, file.FullName);

                SudokuSolutionNode root_node = SudokuSolutionNode.CreateRoot(board);
                SudokuSolutionNode node      = root_node.Solve();

                Assert.IsTrue(!node.Board.IsSolvable, file.Name);
            }
        }
Ejemplo n.º 13
0
        public void Test_Examples_Solvable()
        {
            SudokuOptions.Current.ShowAllSolutions = false;
            SudokuOptions.Current.IncludeBoxes     = true;

            ProgressIndicator pi = new ProgressIndicator(System.Reflection.MethodBase.GetCurrentMethod().Name);

            FileInfo[] files = new DirectoryInfo(Directories.Examples).GetFiles(FileExtensions.XmlZipMask);

            ConcurrentBag <string> unsolvable = new ConcurrentBag <string>();

            ConcurrentCounter counter = new ConcurrentCounter();

            Parallel.ForEach(files, (file) =>
            {
                SudokuBoard board = SudokuBoard.LoadFromFile(file.FullName);
                Assert.IsNotNull(board, file.FullName);

                counter.Increment();
                pi.AddLine((counter.Value * 100 / files.Length).ToString());

                for (int i = 0; i < 4; i++)
                {
                    SudokuSolutionNode root_node = SudokuSolutionNode.CreateRoot(board);
                    SudokuSolutionNode node      = root_node.Solve();

                    if (!node.Board.IsSolved)
                    {
                        unsolvable.Add("unsolvable; rotate_" + i + "; " + file.Name);
                    }

                    board = board.Rotate();
                }
            });

            if (unsolvable.Count > 0)
            {
                foreach (var file in unsolvable)
                {
                    TestContext.WriteLine(file);
                }

                Assert.Fail();
            }
        }
Ejemplo n.º 14
0
        private static void MeasuringAvarageExampleSolvingTime()
        {
            System.Console.WriteLine("Measuring average example solving time:");
            System.Console.WriteLine("");

            FileInfo[] files = new DirectoryInfo(Directories.Examples).GetFiles(FileExtensions.XmlZipMask);

            SudokuBoard[] boards = new SudokuBoard[files.Length];

            for (int i = 0; i < files.Length; i++)
            {
                boards[i] = SudokuBoard.LoadFromFile(files[i].FullName);
            }

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            for (int i = 0; i < boards.Length; i++)
            {
                System.Console.WriteLine(String.Format("Solving {0} from {1}: {2}", i + 1, boards.Length, files[i].Name));

                SudokuSolutionNode node = SudokuSolutionNode.CreateRoot(boards[i]);
                node = node.Solve();

                if (!node.NextBoard.IsSolved)
                {
                    if (SudokuOptions.Current.IncludeBoxes)
                    {
                        System.Console.WriteLine(("ERROR: Can't solve: " + files[i]));
                    }
                    else
                    {
                        System.Console.WriteLine(("ERROR: Can't solve (recheck with boxes): " + files[i]));
                    }
                }
            }

            stopwatch.Stop();

            System.Console.WriteLine("");
            System.Console.WriteLine(("Average solving time per sudoku: " + stopwatch.ElapsedMilliseconds / files.Length + " [ms]"));
        }
Ejemplo n.º 15
0
        private void UpdateNode(SudokuSolutionNode a_node, TreeNode a_treeNode)
        {
            if (a_node == null)
            {
                return;
            }

            a_treeNode = AddNextNode(a_treeNode, a_node);

            if (a_node.Nodes.Any(n => n.Nodes.Any()))
            {
                a_node = a_node.Nodes.First(n => n.Nodes.Any());
            }
            else
            {
                a_node = a_node.Nodes.FirstOrDefault();
            }

            UpdateNode(a_node, a_treeNode);
        }
Ejemplo n.º 16
0
        public void UpdateTree(SudokuSolutionNode a_root, SudokuSolutionNode a_select = null)
        {
            Debug.Assert(a_root.Parent == null);

            BeginUpdate();

            Nodes.Clear();
            UpdateNode(a_root, null);

            EndUpdate();

            if ((a_select != null) && (SolutionNodeToTreeNode(a_select) != null))
            {
                SelectedNode = SolutionNodeToTreeNode(a_select);
            }
            else
            {
                SelectedNode = Nodes.Cast <TreeNode>().Last();
            }
        }
Ejemplo n.º 17
0
        public void Solve(SudokuSolution a_solution = null)
        {
            if (a_solution == null)
            {
                a_solution = SelectedSolutionNode.Nodes.First().Solution;
            }

            SudokuSolutionNode solution_node = TreeNodeToSolutionNode(SelectedNode);

            solution_node = solution_node.Nodes.FirstOrDefault(n => Object.ReferenceEquals(n.Solution, a_solution));

            if (solution_node != null)
            {
                solution_node.Parent.RemoveNodes(solution_node);
            }

            solution_node.Solve();

            UpdateTree(solution_node.Root);
        }
Ejemplo n.º 18
0
        public void Test_Examples_Unsolvable()
        {
            SudokuOptions.Current.ShowAllSolutions = false;
            SudokuOptions.Current.IncludeBoxes     = true;

            FileInfo[] files = new DirectoryInfo(Directories.Examples +
                                                 Path.DirectorySeparatorChar + "Unsolvable").GetFiles(FileExtensions.XmlZipMask);

            ProgressIndicator pi = new ProgressIndicator(System.Reflection.MethodBase.GetCurrentMethod().Name);

            ConcurrentBag <string> solvable = new ConcurrentBag <string>();

            ConcurrentCounter counter = new ConcurrentCounter();

            Parallel.ForEach(files, (file) =>
            {
                counter.Increment();
                pi.AddLine((counter.Value * 100 / files.Length).ToString());

                SudokuBoard board = SudokuBoard.LoadFromFile(file.FullName);
                Assert.IsNotNull(board, file.FullName);

                SudokuSolutionNode root_node = SudokuSolutionNode.CreateRoot(board);
                SudokuSolutionNode node      = root_node.Solve();

                if (node.Board.IsSolved)
                {
                    solvable.Add("solvable; " + file.FullName);
                }
            });

            if (solvable.Count != 0)
            {
                foreach (var line in solvable)
                {
                    TestContext.WriteLine(line);
                }

                Assert.Fail();
            }
        }
Ejemplo n.º 19
0
        public void Test_Solutions_Quantity()
        {
            SudokuOptions.Current.ShowAllSolutions = false;
            SudokuOptions.Current.IncludeBoxes     = true;

            ProgressIndicator pi = new ProgressIndicator(System.Reflection.MethodBase.GetCurrentMethod().Name);

            FileInfo[] files = new DirectoryInfo(Directories.Solutions).GetFiles(FileExtensions.XmlZipMask);

            var solutions = (from file in files.AsParallel()
                             select new
            {
                intermediate_solution = SudokuIntermediateSolution.LoadFromFile(file.FullName),
                fileName = file.FullName,
            }).ToArray();

            solutions.ForEach(example => Assert.IsNotNull(example.intermediate_solution, example.fileName));

            var solutions_gr = (from obj in solutions
                                group obj by obj.intermediate_solution.Solution.Type into gr
                                select(from obj in gr
                                       orderby obj.fileName
                                       select obj).ToArray()).ToArray();

            ConcurrentBag <string> bad_quantities = new ConcurrentBag <string>();

            Parallel.ForEach(solutions_gr, (solution_gr) =>
            {
                pi.AddLine((solutions_gr.IndexOf(solution_gr) * 100 / solutions_gr.Count()).ToString());

                if (new[] { SudokuSolutionType.XWing, SudokuSolutionType.JellyFish,
                            SudokuSolutionType.SwordFish }.Contains(
                        solution_gr.First().intermediate_solution.Solution.Type))
                {
                    if (solution_gr.Count() < 20)
                    {
                        bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type + " - less then 20");
                    }
                    else if (solution_gr.Count() > 20)
                    {
                        bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type + " - more then 20");
                    }
                    else
                    {
                        SudokuOptions.Current.IncludeBoxes = false;

                        var gr1 = (from obj in solution_gr.Take(10)
                                   select obj.intermediate_solution.Solution).ToList();
                        int c1 = SudokuSolutionNode.FilterByOptions(gr1).Count();
                        if (c1 == 0)
                        {
                            bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type +
                                               " - solutions from 1 to 10 doesn't contains any boxes");
                        }
                        if (c1 == 10)
                        {
                            bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type +
                                               " - solutions from 1 to 10 all contains boxes");
                        }

                        SudokuOptions.Current.IncludeBoxes = false;
                        var gr2 = (from obj in solution_gr.Skip(10).Take(10)
                                   select obj.intermediate_solution.Solution).ToList();
                        int c2 = SudokuSolutionNode.FilterByOptions(gr2).Count();
                        if (c2 != 10)
                        {
                            bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type +
                                               " - solutions from 11 to 20 some contains boxes");
                        }
                    }
                }
                else
                {
                    if (solution_gr.Count() < 10)
                    {
                        bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type + " - less then 10");
                    }
                    if (solution_gr.Count() > 10)
                    {
                        bad_quantities.Add(solution_gr.First().intermediate_solution.Solution.Type + " - more then 10");
                    }
                }
            });

            if (solutions_gr.Count() != Enum.GetValues(typeof(SudokuSolutionType)).Length)
            {
                bad_quantities.Add("Not all algorithms was tested");
            }

            if (bad_quantities.Count != 0)
            {
                foreach (var line in bad_quantities)
                {
                    TestContext.WriteLine(line);
                }
            }
        }
Ejemplo n.º 20
0
        public void Test_Solution_Trees_vs_Examples()
        {
            ProgressIndicator pi = new ProgressIndicator(System.Reflection.MethodBase.GetCurrentMethod().Name);

            FileInfo[] files1 = new DirectoryInfo(Directories.Examples).GetFiles(FileExtensions.XmlZipMask);
            FileInfo[] files2 = new DirectoryInfo(Directories.SolutionTrees).GetFiles(FileExtensions.XmlZipMask);

            var not_all = (from file1 in files1
                           where files2.Count(fi => Directories.ConvertName(fi.FullName) == file1.Name) < 4
                           select file1).ToArray();

            var too_much = (from file2 in files2
                            where files1.All(fi => fi.Name != Directories.ConvertName(file2.Name))
                            select file2).ToArray();

            if (not_all.Count() > 0)
            {
                Assert.Fail("Is in 'Examples', but not in 'SolutionTrees' (run project 'SudokuGenerator'): " +
                            not_all.First().FullName);
            }

            if (too_much.Count() > 0)
            {
                Assert.Fail("Is in 'SolutionTrees', but not in 'Examples': " + too_much.First().FullName);
            }

            string dir3 = Directories.SolutionTrees + Path.DirectorySeparatorChar + "Diffrencies";

            new DirectoryInfo(dir3).CreateOrEmpty();

            string dir4 = Directories.SolutionTrees + Path.DirectorySeparatorChar + "Diffrencies" +
                          Path.DirectorySeparatorChar + "Added";

            new DirectoryInfo(dir4).CreateOrEmpty();

            string dir5 = Directories.SolutionTrees + Path.DirectorySeparatorChar + "Diffrencies" +
                          Path.DirectorySeparatorChar + "Removed";

            new DirectoryInfo(dir5).CreateOrEmpty();

            bool b = false;

            ConcurrentBag <string> list = new ConcurrentBag <string>();

            ConcurrentCounter counter = new ConcurrentCounter();

            Parallel.ForEach(files2, (file2, state) =>
            {
                counter.Increment();
                pi.AddLine((counter.Value * 100 / files2.Length).ToString());

                SudokuSolutionNode node2 = SudokuSolutionNode.LoadFromFile(file2.FullName);

                SudokuBoard board = SudokuBoard.LoadFromFile(files1.First(f => f.Name ==
                                                                          Directories.ConvertName(file2.FullName)).FullName);

                board = board.Rotate(ExtractRotateNumber(file2.Name));

                SudokuSolutionNode node1 = SudokuSolutionNode.CreateRoot(board);
                node1.SolveWithStepAll();

                Assert.AreEqual(node1.State, node2.State, file2.FullName);
                Assert.AreEqual(node1.Board, node2.Board, file2.FullName);
                Assert.AreEqual(node1.Solution, node2.Solution, file2.FullName);

                b |= CompareNodes(node1, node2, file2, list, 1, 1);
            });

            if (list.Count != 0)
            {
                string filename = dir3 + Path.DirectorySeparatorChar + "!Diffrencies.txt";

                using (FileStream fs = new FileStream(filename, FileMode.Create))
                {
                    StreamWriter sw = new StreamWriter(fs);
                    list.ForEach(s => sw.WriteLine(s));
                    sw.Flush();
                }

                TestContext.AddResultFile(filename);
            }

            Assert.IsFalse(b);
        }
Ejemplo n.º 21
0
 public EditAction(SolutionsTree a_tree, SudokuSolutionNode a_selected, bool a_edit, Action <bool> a_edit_func)
     : base(a_tree, a_selected)
 {
     m_edit      = a_edit;
     m_edit_func = a_edit_func;
 }
Ejemplo n.º 22
0
 public RotateAction(SolutionsTree a_tree, SolutionsCheckedListBox a_list, SudokuSolutionNode a_selected)
     : base(a_tree, a_selected)
 {
     m_list = a_list;
 }
Ejemplo n.º 23
0
 public SolveAction(SolutionsTree a_tree, SudokuSolutionNode a_selected)
     : base(a_tree, a_selected)
 {
 }
Ejemplo n.º 24
0
 public void InitTree(SudokuBoard a_board)
 {
     UpdateTree(SudokuSolutionNode.CreateRoot(a_board));
 }
Ejemplo n.º 25
0
        private bool CompareNodes(SudokuSolutionNode a_node, SudokuSolutionNode a_expected_node, FileInfo a_fileInfo,
                                  ConcurrentBag <string> a_list, int add_counter, int remove_counter)
        {
            bool b1 = false;

            IEnumerable <SudokuSolutionNode> solutions_added   = null;
            IEnumerable <SudokuSolutionNode> solutions_removed = null;

            if (!a_node.Nodes.Exact(a_expected_node.Nodes))
            {
                solutions_added   = a_node.Nodes.Substract(a_expected_node.Nodes);
                solutions_removed = a_expected_node.Nodes.Substract(a_node.Nodes);

                if (solutions_removed.Count() > 0)
                {
                    solutions_removed = RemoveIfExistsElsewhere(solutions_removed, a_node.Root);
                }
                else
                {
                    solutions_removed = null;
                }

                if (solutions_added.Count() > 0)
                {
                    solutions_added = RemoveIfExistsElsewhere(solutions_added, a_node.Root);
                }
                else
                {
                    solutions_added = null;
                }
            }

            if (solutions_added != null)
            {
                foreach (var added in solutions_added)
                {
                    if (added.Solution != null)
                    {
                        string dir = a_fileInfo.DirectoryName + Path.DirectorySeparatorChar + "Diffrencies" +
                                     Path.DirectorySeparatorChar + "Added";

                        SudokuIntermediateSolution intermediate_solution =
                            new SudokuIntermediateSolution(added.Board, added.NextBoard, added.Solution);

                        intermediate_solution.SaveToFile(dir + Path.DirectorySeparatorChar +
                                                         Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(a_fileInfo.FullName)) +
                                                         "_added_" + add_counter + FileExtensions.XmlZipExt);

                        a_list.Add(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(a_fileInfo.FullName)) +
                                   "_added_" + add_counter + ": " + intermediate_solution.Solution.ToString());

                        add_counter++;

                        b1 = true;
                    }
                }
            }

            if (solutions_removed != null)
            {
                foreach (var removed in solutions_removed)
                {
                    if (removed.Solution != null)
                    {
                        string dir = a_fileInfo.DirectoryName + Path.DirectorySeparatorChar +
                                     "Diffrencies" + Path.DirectorySeparatorChar + "Removed";

                        SudokuIntermediateSolution intermediate_solution =
                            new SudokuIntermediateSolution(removed.Board, removed.NextBoard, removed.Solution);

                        intermediate_solution.SaveToFile(dir + Path.DirectorySeparatorChar +
                                                         Path.GetFileNameWithoutExtension(Path.DirectorySeparatorChar +
                                                                                          Path.GetFileNameWithoutExtension(a_fileInfo.FullName)) + "_removed_" +
                                                         remove_counter + FileExtensions.XmlZipExt);

                        a_list.Add(Path.GetFileNameWithoutExtension(
                                       Path.GetFileNameWithoutExtension(a_fileInfo.FullName)) + "_removed_" +
                                   remove_counter + ": " + intermediate_solution.Solution.ToString());

                        remove_counter++;

                        b1 = true;
                    }
                }
            }

            var node_next     = ((a_node != null) && a_node.Nodes.Any()) ? a_node.Nodes.First() : null;
            var expected_next = ((a_expected_node != null) && a_expected_node.Nodes.Any()) ?
                                a_expected_node.Nodes.First() : null;

            if ((node_next == null) || (expected_next == null))
            {
                return(b1);
            }

            if (!node_next.Solution.Equals(expected_next.Solution))
            {
                var next = a_node.Nodes.FirstOrDefault(n => n.Solution.Equals(expected_next.Solution));

                if (next == null)
                {
                    next = a_expected_node.Nodes.FirstOrDefault(n => n.Solution.Equals(node_next.Solution));

                    if (next != null)
                    {
                        expected_next = next;
                        expected_next.SolveWithStepAll();
                    }
                    else
                    {
                        return(b1);
                    }
                }
                else
                {
                    node_next = next;
                    node_next.SolveWithStepAll();
                }
            }

            if (node_next.Nodes.Any())
            {
                node_next = node_next.Nodes.First();
            }
            else
            {
                return(b1);
            }

            if (expected_next.Nodes.Any())
            {
                expected_next = expected_next.Nodes.First();
            }
            else
            {
                return(b1);
            }

            bool b2 = CompareNodes(node_next, expected_next, a_fileInfo, a_list, add_counter, remove_counter);

            return(b1 | b2);
        }
Ejemplo n.º 26
0
        public void Test_Solution_Trees_Consolidate()
        {
            SudokuOptions.Current.ShowAllSolutions = false;

            ProgressIndicator pi = new ProgressIndicator(System.Reflection.MethodBase.GetCurrentMethod().Name);

            FileInfo[] files = new DirectoryInfo(Directories.SolutionTrees).GetFiles(FileExtensions.XmlZipMask);

            string dir = Directories.SolutionTrees + Path.DirectorySeparatorChar + "Consolidate";

            new DirectoryInfo(dir).CreateOrEmpty();

            int index = 0;
            ConcurrentCounter counter = new ConcurrentCounter();

            Parallel.ForEach(files, (file) =>
            {
                counter.Increment();
                pi.AddLine((counter.Value * 100 / files.Length).ToString());

                SudokuSolutionNode root = SudokuSolutionNode.LoadFromFile(file.FullName);

                foreach (SudokuSolutionNode node in root.GetAllNodesEnumerator())
                {
                    if (node.State != SudokuSolutionNodeState.State)
                    {
                        continue;
                    }

                    var filtered_sols = SudokuSolutionNode.FilterByOptions(node.Nodes.Select(n => n.Solution).ToList());

                    var filtered_nodes = (from n in node.Nodes
                                          where filtered_sols.Contains(n.Solution)
                                          select n).ToList();

                    var new_includes = (from n1 in filtered_nodes
                                        from n2 in filtered_nodes
                                        where SudokuSolutionNode.IsInclude(n1.Solution, n2.Solution, false)
                                        select new { n1, n2 }).ToList();

                    var ignore_pairs = new[]
                    {
                        new [] { SudokuSolutionType.NakedPair, SudokuSolutionType.BoxLineReduction },
                        new [] { SudokuSolutionType.NakedPair, SudokuSolutionType.PointingPair },
                        new [] { SudokuSolutionType.NakedPair, SudokuSolutionType.NakedTriple },
                        new [] { SudokuSolutionType.NakedPair, SudokuSolutionType.NakedQuad },
                        new [] { SudokuSolutionType.NakedTriple, SudokuSolutionType.BoxLineReduction },
                        new [] { SudokuSolutionType.NakedTriple, SudokuSolutionType.NakedQuad },
                        new [] { SudokuSolutionType.NakedTriple, SudokuSolutionType.PointingPair },
                        new [] { SudokuSolutionType.NakedTriple, SudokuSolutionType.PointingTriple },
                        new [] { SudokuSolutionType.NakedQuad, SudokuSolutionType.PointingPair },
                        new [] { SudokuSolutionType.HiddenPair, SudokuSolutionType.HiddenTriple },
                        new [] { SudokuSolutionType.HiddenPair, SudokuSolutionType.HiddenQuad },
                        new [] { SudokuSolutionType.HiddenTriple, SudokuSolutionType.HiddenQuad },
                    };

                    var ignore = from pair in new_includes
                                 from ignore_pair in ignore_pairs
                                 where (((pair.n1.Solution.Type == ignore_pair.First()) &&
                                         (pair.n2.Solution.Type == ignore_pair.Last())) ||
                                        ((pair.n1.Solution.Type == ignore_pair.Last()) &&
                                         (pair.n2.Solution.Type == ignore_pair.First())))
                                 select pair;

                    new_includes = new_includes.Except(ignore).ToList();

                    var doubles = from p1 in new_includes
                                  from p2 in new_includes
                                  where (p1.n1 == p2.n2) &&
                                  (p1.n2 == p2.n1)
                                  select p1;

                    new_includes = new_includes.Except(doubles).ToList();

                    foreach (var pair in new_includes)
                    {
                        SudokuIntermediateSolution intermediate_solution_1 =
                            new SudokuIntermediateSolution(pair.n1.Board, pair.n1.NextBoard, pair.n1.Solution);

                        intermediate_solution_1.SaveToFile(dir + Path.DirectorySeparatorChar + index + "_" +
                                                           Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(file.FullName)) + "_" +
                                                           pair.n1.Solution.Type + FileExtensions.XmlZipExt);

                        SudokuIntermediateSolution intermediate_solution_2 =
                            new SudokuIntermediateSolution(pair.n2.Board, pair.n2.NextBoard, pair.n2.Solution);

                        intermediate_solution_2.SaveToFile(dir + Path.DirectorySeparatorChar + index + "_" +
                                                           Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(file.FullName)) + "_" +
                                                           pair.n2.Solution.Type + FileExtensions.XmlZipExt);

                        index++;
                    }
                }
            });

            Assert.IsTrue(index == 0);
        }
Ejemplo n.º 27
0
        private static void GenerateAllSolutions(GenerationMethod a_method)
        {
            System.Console.WriteLine();
            System.Console.WriteLine("Generating solutions...");
            System.Console.WriteLine();

            string dir = Directories.SolutionTrees + Path.DirectorySeparatorChar + "All";

            new DirectoryInfo(dir).CreateOrEmpty();

            FileInfo[] files1 = new DirectoryInfo(Directories.Examples).GetFiles(FileExtensions.XmlZipMask);
            FileInfo[] files2 = new DirectoryInfo(Directories.SolutionTrees).GetFiles(FileExtensions.XmlZipMask);

            var not_all = (from file1 in files1
                           where files2.Count(fi => Directories.ConvertName(fi.FullName) == file1.Name) < 4
                           select file1).ToArray();

            var too_much = (from file2 in files2
                            where files1.All(fi => fi.Name != Directories.ConvertName(file2.Name))
                            select file2).ToArray();


            if (not_all.Count() > 0)
            {
                System.Console.WriteLine("Is in 'Examples', but not in 'SolutionTrees' (run project 'SudokuGenerator'): " + not_all.First().FullName);
                System.Console.ReadKey(true);
                return;
            }

            if (too_much.Count() > 0)
            {
                System.Console.WriteLine("Is in 'SolutionTrees', but not in 'Examples': " + too_much.First().FullName);
                System.Console.ReadKey(true);
                return;
            }

            FileInfo[] files = (from file in new DirectoryInfo(Directories.SolutionTrees).GetFiles(FileExtensions.XmlZipMask)
                                group file by Directories.ConvertName(file.Name) into gr
                                select gr.First()).ToArray();

            ShowProgress(0, 70);

            ConcurrentCounter counter = new ConcurrentCounter();

            Parallel.ForEach(files, (file) =>
            {
                SudokuSolutionNode root = SudokuSolutionNode.LoadFromFile(file.FullName);

                string file_name = Path.GetFileNameWithoutExtension(Directories.ConvertName(file.Name));

                Dictionary <SudokuSolutionType, int> counters = new Dictionary <SudokuSolutionType, int>();
                Dictionary <SudokuSolutionType, List <SudokuSolutionNode> > lists = new Dictionary <SudokuSolutionType, List <SudokuSolutionNode> >();

                foreach (var type in Enum.GetValues(typeof(SudokuSolutionType)).Cast <SudokuSolutionType>())
                {
                    if (type == SudokuSolutionType.MarkImpossibles)
                    {
                        continue;
                    }
                    if (type == SudokuSolutionType.MarkSolved)
                    {
                        continue;
                    }
                    if (type == SudokuSolutionType.SinglesInUnit)
                    {
                        continue;
                    }

                    new DirectoryInfo(dir + Path.DirectorySeparatorChar + type).CreateOrEmpty();
                    lists[type]    = new List <SudokuSolutionNode>();
                    counters[type] = 1;
                }

                foreach (var list in lists.Values)
                {
                    list.Clear();
                }

                foreach (SudokuSolutionNode node in root.GetAllNodesEnumerator())
                {
                    if (node.State != SudokuSolutionNodeState.State)
                    {
                        continue;
                    }

                    var nodes = (from n in node.Nodes
                                 where (n.Solution.Type != SudokuSolutionType.MarkImpossibles) &&
                                 (n.Solution.Type != SudokuSolutionType.MarkSolved) &&
                                 (n.Solution.Type != SudokuSolutionType.SinglesInUnit)
                                 select n).ToList();

                    var sols = SudokuSolutionNode.FilterByOptions(nodes.Select(n => n.Solution).ToList());

                    var nodes_gr = (from n in nodes
                                    where sols.Contains(n.Solution)
                                    group n by n.Solution.Type into gr
                                    select gr.ToList()).ToList();


                    if ((a_method == GenerationMethod.OneType) || (a_method == GenerationMethod.OneSolution))
                    {
                        bool one_type = nodes_gr.Count(gr => gr.Any()) == 1;

                        if (!one_type)
                        {
                            continue;
                        }
                    }

                    if (a_method == GenerationMethod.OneSolution)
                    {
                        bool one_solution = nodes_gr.Count(gr => gr.Count == 1) == 1;

                        if (!one_solution)
                        {
                            continue;
                        }
                    }

                    foreach (var n in nodes)
                    {
                        lists[n.Solution.Type].Add(n);
                    }
                }

                foreach (var list in lists.Values)
                {
                    var uniques = from n in list
                                  group n by n.Solution into gr
                                  select gr.First();

                    var exclude = from n1 in uniques
                                  from n2 in uniques
                                  where !Object.ReferenceEquals(n1, n2) &&
                                  n1.Solution.Removed.Contains(n2.Solution.Removed, Comparators.SudokuNumberRowColComparer.Instance) &&
                                  n1.Solution.Stayed.Contains(n2.Solution.Stayed, Comparators.SudokuNumberRowColComparer.Instance) &&
                                  n1.Solution.ColorUnits.Equals(n2.Solution.ColorUnits)
                                  select n2;

                    var sols = uniques.Except(exclude);

                    foreach (var n in sols)
                    {
                        SudokuIntermediateSolution intermediate_solution = new SudokuIntermediateSolution(n.Board, n.NextBoard, n.Solution);

                        intermediate_solution.SaveToFile(dir + Path.DirectorySeparatorChar + n.Solution.Type + Path.DirectorySeparatorChar +
                                                         file_name + " - " + counters[n.Solution.Type]++ + FileExtensions.XmlZipExt);
                    }
                }

                counter.Increment();
                lock (counter)
                {
                    ShowProgress(counter.Value * 70 / files.Length, 70);
                }
            });
        }
Ejemplo n.º 28
0
        private static void MeasuringAverageAlgorithmSolvingTime()
        {
            const int REPEATS = 2;

            System.Console.WriteLine("Measuring average algorithm solving time:");
            System.Console.WriteLine("");

            FileInfo[] files = new DirectoryInfo(Directories.Solutions).GetFiles(FileExtensions.XmlZipMask);

            var solutions1 = from file in files.AsParallel()
                             select new
            {
                intermediate_solution = SudokuIntermediateSolution.LoadFromFile(file.FullName),
                fileName = file.FullName
            };

            var solutions2 = (from solution in solutions1
                              group solution by solution.intermediate_solution.Solution.Type into g
                              select(from obj in g
                                     orderby obj.fileName
                                     select obj).ToArray()).ToArray();

            foreach (var sols_gr in solutions2)
            {
                var sols = SudokuSolutionNode.FilterByOptions(sols_gr.Select(gr => gr.intermediate_solution.Solution).ToList());

                if (sols_gr.Length == 20)
                {
                    if (SudokuOptions.Current.IncludeBoxes)
                    {
                        sols = sols.Take(10).ToList();
                    }
                    else
                    {
                        sols = sols.Skip(10).Take(10).ToList();
                    }
                }

                var sols_gr2 = (from gr in sols_gr
                                where sols.Contains(gr.intermediate_solution.Solution)
                                select gr).ToList();

                System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                stopwatch.Start();

                foreach (var solution in sols_gr2)
                {
                    SudokuIntermediateSolution intermediate_solution = solution.intermediate_solution;

                    bool bError = false;

                    for (int i = 0; i < REPEATS; i++)
                    {
                        for (int j = 0; j < 4; j++)
                        {
                            if (!intermediate_solution.Test(false))
                            {
                                bError = true;
                            }

                            intermediate_solution = intermediate_solution.Rotate();
                        }
                    }

                    if (bError)
                    {
                        System.Console.WriteLine("Can't solve: {0}", solution.fileName);
                    }
                }

                stopwatch.Stop();

                double time = stopwatch.ElapsedMilliseconds * 1.0 / sols_gr.Length / REPEATS / 4;

                s_algorithmToTime[sols_gr.First().intermediate_solution.Solution.Type] = time;

                System.Console.WriteLine("{0} ({1}): {2} [ms]", sols_gr.First().intermediate_solution.Solution.Type, sols_gr.Length, time.ToString("G4"));
            }
        }