Beispiel #1
0
        public void BruteForce_SingleState_FullSolve()
        {
            //all right, now the real test
            List <Cell> SolvedCells   = BoardTest.SolvedSudokuPuzzle1();
            Board       UnSolvedBoard = new Board(BoardTest.UnsolvedSudokuPuzzle1());

            BruteForceSolver Solver = new BruteForceSolver();

            Solver.SingleStateBruteForceSolve(ref UnSolvedBoard);



            Assert.IsTrue(BoardTest.CellListsAreEqual(UnSolvedBoard.Cells, SolvedCells),
                          "Brute force failed to solve the first test board, its result: " + UnSolvedBoard.PrintBoard());



            SolvedCells   = BoardTest.SolvedSudokuPuzzle2();
            UnSolvedBoard = new Board(BoardTest.UnsolvedSudokuPuzzle2());

            Solver.SingleStateBruteForceSolve(ref UnSolvedBoard);


            Assert.IsTrue(BoardTest.CellListsAreEqual(UnSolvedBoard.Cells, SolvedCells),
                          "Brute force failed to solve the second test board, its result: " + UnSolvedBoard.PrintBoard());
        }
        public void TestName()
        {
            // create the solver.
            var solver = new BruteForceSolver();

            Assert.AreEqual("BF", solver.Name);
        }
Beispiel #3
0
        public void SimpleTest()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9000, 100, new List <Item>
            {
                new Item(18, 114, 0), new Item(42, 136, 1), new Item(88, 192, 2), new Item(3, 223, 3)
            });

            IKnapsackSolver solver = new BruteForceSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(473, solve);

            IKnapsackSolver solver2 = new BranchAndBoundSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(473, solve2);

            IKnapsackSolver solver4 = new GeneticSolver(100, 100, new RouletteWheelSelection(), 0.01, 0.8, 0, false, false);

            solver4.Solve(problem);

            IKnapsackSolver solver5 = new FPTASSolver(0.9);

            solver5.Solve(problem);
        }
Beispiel #4
0
    public void Run()
    {
        var random = new Random();

        for (var n = 1; n < 20; n++)
        {
            var xs = new long[n];

            for (var k = 1; k < n + 2; k++)
            {
                for (var i = 0; i < xs.Length; i++)
                {
                    xs[i] = random.Next(1, n + 1);
                }

                var bruteForceSolver = new BruteForceSolver(n, k, xs);
                var fastSolver       = new FastSolver(n, k, xs);

                var expected = bruteForceSolver.Solve();
                var actual   = fastSolver.Solve();
                if (actual != expected)
                {
                    Console.WriteLine("{0} {1}", n, k);
                    Console.WriteLine(string.Join(" ", xs));
                    Console.WriteLine("Expected {0}, actual {1}", expected, actual);
                    bruteForceSolver.Solve();
                    fastSolver.Solve();
                }
            }
        }
    }
Beispiel #5
0
        public void SimpleTest5()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9000, 100, new List <Item>
            {
                new Item(27, 38, 0),
                new Item(2, 86, 1),
                new Item(41, 112, 2),
                new Item(1, 0, 3),
                new Item(25, 66, 4),
                new Item(1, 97, 5),
                new Item(34, 195, 6),
                new Item(3, 85, 7),
                new Item(50, 42, 8),
                new Item(12, 223, 9)
            });

            IKnapsackSolver solver = new BruteForceSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(798, solve);

            IKnapsackSolver solver2 = new BranchAndBoundSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(798, solve2);

            IKnapsackSolver solver3 = new DynamicByCostSolver();
            int             solve3  = solver3.Solve(problem);

            Assert.AreEqual(798, solve3);
        }
Beispiel #6
0
        public void BruteForce_SingleState_ReviseGuessTest()
        {
            List <Cell> SolvedCells     = BoardTest.SolvedSudokuPuzzle1();
            Board       MissingOneBoard = new Board(SolvedCells);

            //Blanking out values so the first one it comes across has 2 possible valid values, and the first one would be wrong
            //i.e. force it to "guess" and then backtrack
            int OriginalValue1 = MissingOneBoard.Cells[2].Value;

            MissingOneBoard.Cells[2] = new Cell(0);
            int OriginalValue2 = MissingOneBoard.Cells[11].Value;

            MissingOneBoard.Cells[11] = new Cell(0);
            int OriginalValue3 = MissingOneBoard.Cells[8].Value;

            MissingOneBoard.Cells[8] = new Cell(0);
            BruteForceSolver Solver = new BruteForceSolver();

            Solver.SingleStateBruteForceSolve(ref MissingOneBoard);

            Assert.IsTrue(MissingOneBoard.Cells[2].Value == OriginalValue1 &&
                          MissingOneBoard.Cells[11].Value == OriginalValue2 &&
                          MissingOneBoard.Cells[8].Value == OriginalValue3,
                          "Brute force solver Revision failed to fill in 3 scattered values missing from completed board: " +
                          OriginalValue1 + " is now " + MissingOneBoard.Cells[2].Value + ", " +
                          OriginalValue2 + " is now " + MissingOneBoard.Cells[11].Value + ", " +
                          OriginalValue3 + " is now " + MissingOneBoard.Cells[8].Value);
        }
Beispiel #7
0
        public void Solve_ShouldReturnCorrectValue_IfAllItemsShouldBeInBag()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9005, 100, new List <Item>
            {
                new Item(12, 66, 0), new Item(52, 167, 1), new Item(14, 150, 2), new Item(3, 180, 3)
            });

            IKnapsackSolver solver = new RatioHeuristicSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(563, solve);

            IKnapsackSolver solver2 = new BruteForceSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(563, solve2);

            IKnapsackSolver solver3 = new BranchAndBoundSolver();
            int             solve3  = solver3.Solve(problem);

            Assert.AreEqual(563, solve3);

            IKnapsackSolver solver4 = new DynamicByCostSolver();
            int             solve4  = solver4.Solve(problem);

            Assert.AreEqual(563, solve4);
        }
Beispiel #8
0
        public void BruteForce_Recursive_FullSolve()
        {
            string TestType = "Recursive Brute force ";
            bool   MultipleSolutionsFound = false;

            //all right, now the real test
            List <Cell> SolvedCells   = BoardTest.SolvedSudokuPuzzle1();
            Board       UnSolvedBoard = new Board(BoardTest.UnsolvedSudokuPuzzle1());

            BruteForceSolver Solver = new BruteForceSolver();

            Solver.RecursiveBruteForceSolve(ref UnSolvedBoard, ref MultipleSolutionsFound);



            Assert.IsTrue(BoardTest.CellListsAreEqual(UnSolvedBoard.Cells, SolvedCells),
                          TestType + "failed to solve the first test board, its result: " + UnSolvedBoard.PrintBoard());
            Assert.IsFalse(MultipleSolutionsFound,
                           TestType + "said there were multiple solutions on a board with just one");



            SolvedCells   = BoardTest.SolvedSudokuPuzzle2();
            UnSolvedBoard = new Board(BoardTest.UnsolvedSudokuPuzzle2());

            Solver.RecursiveBruteForceSolve(ref UnSolvedBoard, ref MultipleSolutionsFound);


            Assert.IsTrue(BoardTest.CellListsAreEqual(UnSolvedBoard.Cells, SolvedCells),
                          TestType + "failed to solve the second test board, its result: " + UnSolvedBoard.PrintBoard());
            Assert.IsFalse(MultipleSolutionsFound,
                           TestType + "said there were multiple solutions on a board with just one");
        }
        public void TestSolver2()
        {
            // create a problem with only one customer.
            var problem = TSPHelper.CreateTSP(0, 1, 2, 10);

            // create the solver.
            var solver   = new BruteForceSolver();
            var solution = solver.Solve(problem, new TSPObjective());

            // verify solution.
            Assert.AreEqual(new int[] { 0, 1 }, solution.ToArray());
        }
Beispiel #10
0
        private void btnRunAsync_Click(object sender, RoutedEventArgs e)
        {
            output_to_file = false;
            tokensource    = new CancellationTokenSource();
            if (model != null && model.Requests.Count > 0)
            {
                btnRunAsync.IsEnabled = false;
                set_model_parameter();
                //clear optimizer Output:
                txtOptimizerOutput.Text = "";

                Solver.Solver s = null;
                if (rbGeneticAlgorithm.IsChecked == true)
                {
                    s = new GeneticSolver(model, Convert.ToInt32(txtGenerations.Text), Convert.ToInt32(txtPopulationSize.Text), Convert.ToInt32(txtMutationProbability.Text), Convert.ToInt32(txtReportProgress.Text));
                }
                if (rbBruteForce.IsChecked == true)
                {
                    if (model.GetNumberOfElements() > 11)
                    {
                        MessageBox.Show("I´m sorry Dave, I`m afraid I can`t do that!");
                    }
                    else
                    {
                        s = new BruteForceSolver(model);
                    }
                }
                if (rbSimulatedAnnealing.IsChecked == true)
                {
                    s = new SimulatedAnnealingSolver(model, Convert.ToInt32(txtStartTemp.Text), Convert.ToInt32(txtSteps.Text), Convert.ToInt32(txtReportProgress.Text), Convert.ToInt32(txtParallelAnnealings.Text));
                }
                if (rbGreedy.IsChecked == true)
                {
                    s = new GreedySolver(model);
                }
                if (rbInsertion.IsChecked == true)
                {
                    s = new NearestInsertionSolver(model);
                }
                if (rbSavings.IsChecked == true)
                {
                    s = new SavingsSolver(model);
                }

                if (s != null)
                {
                    Start_Optimizer(s);
                }
            }
        }
        public void Test1(double stock, double[] orderLens, int[] orderNums, int nRequiredBar)
        {
            // Input
            double rawBarHeightInput    = stock;
            var    requiredBarSetInputs = new List <BarSet>();

            for (int i = 0; i < orderLens.Length; i++)
            {
                requiredBarSetInputs.Add(new BarSet(orderLens[i], orderNums[i]));
            }

            var pttnRst = BruteForceSolver.solveRecursive(requiredBarSetInputs, rawBarHeightInput);
            var nBar    = pttnRst.fst;

            Assert.Equal(4, nBar);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Insert the board hash as 1 long line:");
            var hash = System.Console.ReadLine();

            var boardHash = new BoardHash();
            var stats     = new BoardStatistics(boardHash.LoadFromHash(hash), new PossibilityCalculator(boardHash.LoadFromHash(hash)));

            System.Console.WriteLine($"\n\nStarting solving. There are {stats.GetPossibilities()} possibilities..");

            var solver = new BruteForceSolver();
            var result = solver.Solve((new BoardHash()).LoadFromHash(hash));

            System.Console.WriteLine($"Solved in {solver.Attempts} attempts.\n\n");
            OutputBoard(result);
        }
Beispiel #13
0
        public void BruteForce_Recursive_EmptyPuzzle()
        {
            string TestType = "Recursive Brute force ";
            bool   MultipleSolutionsFound = false;

            Board UnSolvedBoard = new Board(BoardTest.EmptySudokuPuzzle());

            BruteForceSolver Solver = new BruteForceSolver();

            Solver.RecursiveBruteForceSolve(ref UnSolvedBoard, ref MultipleSolutionsFound);


            Assert.IsTrue(UnSolvedBoard.IsValid() && UnSolvedBoard.IsComplete(),
                          TestType + "failed to solve the first test board, its result: " + UnSolvedBoard.PrintBoard());
            Assert.IsTrue(MultipleSolutionsFound,
                          TestType + "failed to detect multiple solutions in an empty sudoku grid");
        }
        public void TestSolverClosed()
        {
            // create the problem and make sure 0->1->2->3->4 is the solution.
            var problem = TSPHelper.CreateTSP(0, 0, 5, 10);

            problem.Weights[0][1] = 1;
            problem.Weights[1][2] = 1;
            problem.Weights[2][3] = 1;
            problem.Weights[3][4] = 1;
            problem.Weights[4][0] = 1;

            // create the solver.
            var solver   = new BruteForceSolver();
            var solution = solver.Solve(problem, new TSPObjective());

            // verify solution.
            Assert.AreEqual(new int[] { 0, 1, 2, 3, 4 }, solution.ToArray());
        }
Beispiel #15
0
    public void Run()
    {
        var bruteForce = new BruteForceSolver();
        var fast       = new FastSolver();

        for (var n = 3; n < 10; n++)
        {
            foreach (var ps in Quiz.AllPropositions(n))
            {
                var s        = new string(ps);
                var expected = bruteForce.Solve(n, s);
                var actual   = fast.Solve(n, s);
                if (expected != actual)
                {
                    System.Diagnostics.Debug.Assert(false);
                }
            }
        }
    }
Beispiel #16
0
        public override IEnumerable <ISolvingTechnique> FindAll(Grid grid)
        {
            BruteForceSolver solver = new BruteForceSolver();
            var solution            = solver.Solve(grid) ?? solver.SolveGivens(grid);

            if (solution == null)
            {
                yield return(new NoSolution());

                yield break;
            }

            var invalidSolutions = Position.Positions.Where(pos => grid.HasValue(pos) &&
                                                            grid.GetValue(pos) != solution.GetValue(pos));

            if (invalidSolutions.Any())
            {
                yield return(new InvalidValue(invalidSolutions));
            }
        }
Beispiel #17
0
        public void SimpleTest4()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9012, 100, new List <Item>
            {
                new Item(51, 87, 0), new Item(5, 198, 1), new Item(19, 40, 2), new Item(81, 47, 3)
            });

            IKnapsackSolver solver = new BruteForceSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(325, solve);

            IKnapsackSolver solver2 = new BranchAndBoundSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(325, solve2);

            IKnapsackSolver solver3 = new DynamicByCostSolver();
            int             solve3  = solver3.Solve(problem);

            Assert.AreEqual(325, solve3);
        }
Beispiel #18
0
        public void SimpleTestWithZeroElem()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9000, 100, new List <Item>
            {
                new Item(18, 0, 0), new Item(42, 136, 1), new Item(88, 0, 2), new Item(3, 223, 3)
            });

            IKnapsackSolver solver = new BruteForceSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(359, solve);

            IKnapsackSolver solver2 = new BranchAndBoundSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(359, solve2);

            IKnapsackSolver solver3 = new DynamicByCostSolver();
            int             solve3  = solver3.Solve(problem);

            Assert.AreEqual(359, solve3);
        }
Beispiel #19
0
        public void SimpleTest3()
        {
            KnapsackProblemModel problem = new KnapsackProblemModel(9013, 100, new List <Item>
            {
                new Item(11, 166, 0), new Item(24, 165, 1), new Item(50, 74, 2), new Item(21, 100, 3)
            });

            IKnapsackSolver solver = new BruteForceSolver();
            int             solve  = solver.Solve(problem);

            Assert.AreEqual(431, solve);

            IKnapsackSolver solver2 = new BranchAndBoundSolver();
            int             solve2  = solver2.Solve(problem);

            Assert.AreEqual(431, solve2);

            IKnapsackSolver solver3 = new DynamicByCostSolver();
            int             solve3  = solver3.Solve(problem);

            Assert.AreEqual(431, solve3);
        }
Beispiel #20
0
        public void SolvePuzzle()
        {
            this.solving = true;

            if (!this.BruteForceSolve)
            {
                LogicalSolver.Solve(this);

                // not solved, do we fall back?
                Debugger.Break();
            }

            else
            {
                LogicalSolver.SetCellValueForNakedSingles(this);

                this.Solved = BruteForceSolver.Solve(this);
                if (!this.Solved)
                {
                    Debugger.Break();
                }
            }
        }
        /// <summary>
        /// Processes a TSP and reports errors.
        /// </summary>
        /// <param name="file">File name of TSP being processed.</param>
        private void ProcessTsp(string file)
        {
            System.Diagnostics.Debug.WriteLine($"Loading TSP at path {file} ...\n");

            // Try convert text to TSP
            var success = Interface.TryTextToTsp(file, out var tsp);

            // If conversion was a success
            if (success)
            {
                // Print TSP info to debug console
                tsp.Print();

                // Update name of problem on graph
                this.problemName.Text = tsp.Name;

                // Create solver and event handlers
                Solver solver = null;
                ProgressChangedEventHandler    updateHandler     = null;
                RunWorkerCompletedEventHandler completionHandler = null;
                int drawDelay = 0;

                // Set solvers and event handlers based on the chosen setting
                if (bruteForceRadioButton.IsChecked == true)
                {
                    solver = new BruteForceSolver();

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (bfsRadioButton.IsChecked == true || dfsRadioButton.IsChecked == true)
                {
                    var goal = Convert.ToInt32(searchGoal.Text);

                    if (bfsRadioButton.IsChecked == true)
                    {
                        solver = new BfsSolver();
                    }
                    else
                    {
                        solver = new DfsSolver();
                    }

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (greedyRadioButton.IsChecked == true)
                {
                    solver            = new GreedySolver();
                    updateHandler     = GreedyProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else if (geneticRadioButton.IsChecked == true)
                {
                    solver            = new GeneticSolver();
                    updateHandler     = GeneticProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else
                {
                    MessageBox.Show("No solution method was selected.");
                    return;
                }

                if (progressCheckBox.IsChecked == true)
                {
                    // Update continously
                    solver.ProgressChanged += updateHandler;
                }
                else
                {
                    // Update only at the end
                    solver.RunWorkerCompleted += completionHandler;
                }

                var workerArgs = new Tuple <Tsp, int>(tsp, progressCheckBox.IsChecked == true ? drawDelay : 0);

                // Run solver and draw output
                solver.RunWorkerAsync(workerArgs);
            }
            // If conversion failed
            else
            {
                MessageBox.Show($"Could not convert TSP from text file: \n\n{file}");
            }
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            decimal   frequency = Stopwatch.Frequency;

            if (CommandLine.Parser.Default.ParseArguments(args, Options))
            {
                TextWriter reportWriter = Options.OutputFilePath == null ? Console.Out : new StreamWriter(Options.OutputFilePath);

                VerboseLog("Data parsing ...");

                DataParser parser = new DataParser();
                List <KnapsackProblemModel>          knapsackProblemModels        = parser.ParseProblem(Options.InputFiles);
                Dictionary <int, int>                knownResults                 = null;
                Dictionary <int, Tuple <int, long> > bruteForceResults            = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > costToRatioHeuristicsResults = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > branchAndBoundResults        = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > dynamicByCostResults         = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > fptasResults                 = new Dictionary <int, Tuple <int, long> >();
                Dictionary <int, Tuple <int, long> > geneticResults               = new Dictionary <int, Tuple <int, long> >();

                if (Options.ResultFiles != null)
                {
                    knownResults = parser.ParseResults(Options.ResultFiles);
                }

                VerboseLog("Done.");

                IKnapsackSolver bruteForceSolver     = new BruteForceSolver();
                IKnapsackSolver ratioHeuristicSolver = new RatioHeuristicSolver();
                IKnapsackSolver branchAndBoundSolver = new BranchAndBoundSolver();
                IKnapsackSolver dynamicByCostSolve   = new DynamicByCostSolver();
                IKnapsackSolver fptasSolver          = null;
                IKnapsackSolver geneticSolver        = null;

                if (Options.FPTAS)
                {
                    fptasSolver = new FPTASSolver(Options.FPTASAccuracy);
                }
                if (Options.Genetics)
                {
                    ISelectionMethod selectionMethod = null;
                    switch (Options.SelectionMethod)
                    {
                    case "roulette": selectionMethod = new RouletteWheelSelection();
                        break;

                    case "rank": selectionMethod = new RankSelection();
                        break;

                    case "elitary": selectionMethod = new EliteSelection();
                        break;

                    default: Console.WriteLine("Wrong selection method for genetics");
                        break;
                    }

                    if (selectionMethod == null)
                    {
                        return;
                    }


                    if (Options.GeneticMetaoptimization)
                    {
                        //Random selection portion
                        for (int i = 0; i < 100; i++)
                        {
                            double randomSelectionPortion = (i * 0.001) + 0;
                            //Crossover rate
                            for (int j = 0; j < 1; j++)
                            {
                                double crossoverRate = (j * 0.03) + 0.22;
                                //Mutation rate
                                for (int k = 0; k < 1; k++)
                                {
                                    double mutationRate = (k * 0.04) + 0.87;

                                    geneticSolver = new GeneticSolver(Options.PopulationSize, Options.IterationsCount, selectionMethod, mutationRate, crossoverRate, randomSelectionPortion, false, false);
                                    geneticResults.Clear();
                                    foreach (KnapsackProblemModel problem in knapsackProblemModels)
                                    {
                                        int result = 0;
                                        try
                                        {
                                            stopwatch.Restart();
                                            result = geneticSolver.Solve(problem);
                                            stopwatch.Stop();
                                        }
                                        catch (Exception ex)
                                        {
                                        }

                                        geneticResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                                    }

                                    decimal totalTime  = 0;
                                    decimal totalError = 0;

                                    foreach (KnapsackProblemModel problem in knapsackProblemModels)
                                    {
                                        int problemId            = problem.ProblemId;
                                        Tuple <int, long> result = geneticResults[problemId];
                                        totalTime  += (result.Item2 / frequency);
                                        totalError += CalculateRelativeError(knownResults[problemId], result.Item1);
                                    }

                                    decimal averageError = totalError / knapsackProblemModels.Count;

                                    reportWriter.WriteLine(randomSelectionPortion + "," + crossoverRate + "," + mutationRate + "," + totalTime + "," + averageError);
                                }
                            }
                        }
                    }

                    geneticSolver = new GeneticSolver(Options.PopulationSize, Options.IterationsCount, selectionMethod, Options.MutationRate, Options.CrossoverRate, Options.RandomSelectionPortion, Options.DiversityCheck, true);
                }

                VerboseLog("Solving JIT instance");
                KnapsackProblemModel jitProblem = new KnapsackProblemModel(-1, 100, new List <Item>
                {
                    new Item(18, 114, 0), new Item(42, 136, 1), new Item(88, 192, 2), new Item(3, 223, 3)
                });

                bruteForceSolver.Solve(jitProblem);
                ratioHeuristicSolver.Solve(jitProblem);
                branchAndBoundSolver.Solve(jitProblem);
                dynamicByCostSolve.Solve(jitProblem);

                if (fptasSolver != null)
                {
                    fptasSolver.Solve(jitProblem);
                }

                if (geneticSolver != null)
                {
                    geneticSolver.Solve(jitProblem);
                }

                VerboseLog("Calculation started");



                foreach (KnapsackProblemModel problem in knapsackProblemModels)
                {
                    VerboseLog("Solving problem:");
                    VerboseLog(problem);

                    int knownResult = -1;
                    if (knownResults != null)
                    {
                        knownResult = knownResults[problem.ProblemId];
                        VerboseLog("Result should be: " + knownResult);
                    }

                    if (Options.BruteForce)
                    {
                        VerboseLog("Brute force solver ...");

                        stopwatch.Restart();
                        int result = bruteForceSolver.Solve(problem);
                        stopwatch.Stop();

                        bruteForceResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));

                        if (knownResult != -1 && result != knownResult)
                        {
                            Console.WriteLine("ERROR - Brute force algorithm not accurate for problem " + problem);
                            Environment.Exit(1);
                        }
                    }

                    if (Options.BranchAndBound)
                    {
                        VerboseLog("Branch and bound solver ...");

                        stopwatch.Restart();
                        int result = branchAndBoundSolver.Solve(problem);
                        stopwatch.Stop();

                        branchAndBoundResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));

                        if (knownResult != -1 && result != knownResult)
                        {
                            Console.WriteLine("ERROR - Branch and bound algorithm not accurate for problem " + problem);
                            Environment.Exit(1);
                        }
                    }

                    if (Options.DynamicByCost)
                    {
                        VerboseLog("Dynamic by cost solver ...");

                        stopwatch.Restart();
                        int result = dynamicByCostSolve.Solve(problem);
                        stopwatch.Stop();

                        dynamicByCostResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));

                        if (knownResult != -1 && result != knownResult)
                        {
                            Console.WriteLine("ERROR - Dynamic by cost algorithm not accurate for problem " + problem);
                            Environment.Exit(1);
                        }
                    }

                    if (Options.CostToRatioHeuristics)
                    {
                        VerboseLog("Ratio heuristics solver ...");

                        stopwatch.Restart();
                        int result = ratioHeuristicSolver.Solve(problem);
                        stopwatch.Stop();

                        costToRatioHeuristicsResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                    }

                    if (Options.FPTAS)
                    {
                        VerboseLog("FPTAS solver ...");

                        if (fptasSolver != null)
                        {
                            stopwatch.Restart();
                            int result = fptasSolver.Solve(problem);
                            stopwatch.Stop();

                            fptasResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                        }
                    }

                    if (Options.Genetics)
                    {
                        VerboseLog("Genetics solver ...");

                        if (geneticSolver != null)
                        {
                            stopwatch.Restart();
                            int result = geneticSolver.Solve(problem);
                            stopwatch.Stop();

                            geneticResults.Add(problem.ProblemId, new Tuple <int, long>(result, stopwatch.ElapsedTicks));
                        }
                    }

                    VerboseLog("Problem solved.");
                }

                reportWriter.Write("Problem ID;Items count");
                if (knownResults != null)
                {
                    reportWriter.Write(";Known result");
                }
                if (Options.BruteForce)
                {
                    reportWriter.Write(";Brute force result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.CostToRatioHeuristics)
                {
                    reportWriter.Write(";Cost to weight ration heuristics result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.BranchAndBound)
                {
                    reportWriter.Write(";Branch and bound result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.DynamicByCost)
                {
                    reportWriter.Write(";Dynamic programming by cost result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                if (Options.FPTAS)
                {
                    reportWriter.Write(";FPTAS result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error;Max possible error");
                    }
                }
                if (Options.Genetics)
                {
                    reportWriter.Write(";Genetics result;Time [s]");
                    if (knownResults != null)
                    {
                        reportWriter.Write(";Relative error");
                    }
                }
                reportWriter.WriteLine();

                foreach (KnapsackProblemModel problem in knapsackProblemModels)
                {
                    var problemId = problem.ProblemId;
                    reportWriter.Write(problemId);
                    reportWriter.Write(";" + problem.Items.Count);
                    if (knownResults != null)
                    {
                        reportWriter.Write(";" + knownResults[problemId]);
                    }
                    if (Options.BruteForce)
                    {
                        Tuple <int, long> bruteForceResult = bruteForceResults[problemId];
                        reportWriter.Write(";" + bruteForceResult.Item1 + ";" + bruteForceResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], bruteForceResult.Item1));
                        }
                    }
                    if (Options.CostToRatioHeuristics)
                    {
                        Tuple <int, long> heuristicsResult = costToRatioHeuristicsResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    if (Options.BranchAndBound)
                    {
                        Tuple <int, long> heuristicsResult = branchAndBoundResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    if (Options.DynamicByCost)
                    {
                        Tuple <int, long> heuristicsResult = dynamicByCostResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    if (Options.FPTAS)
                    {
                        Tuple <int, long> heuristicsResult = fptasResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                            reportWriter.Write(";" + ((FPTASSolver)fptasSolver).GetMaximumError(problem));
                        }
                    }
                    if (Options.Genetics)
                    {
                        Tuple <int, long> heuristicsResult = geneticResults[problemId];
                        reportWriter.Write(";" + heuristicsResult.Item1 + ";" + heuristicsResult.Item2 / frequency);
                        if (knownResults != null)
                        {
                            reportWriter.Write(";" + CalculateRelativeError(knownResults[problemId], heuristicsResult.Item1));
                        }
                    }
                    reportWriter.WriteLine();
                }

                if (Options.Genetics)
                {
                    decimal totalTime  = 0;
                    decimal totalError = 0;

                    foreach (KnapsackProblemModel problem in knapsackProblemModels)
                    {
                        int problemId            = problem.ProblemId;
                        Tuple <int, long> result = geneticResults[problemId];
                        totalTime  += (result.Item2 / frequency);
                        totalError += CalculateRelativeError(knownResults[problemId], result.Item1);
                    }

                    decimal averageError = totalError / knapsackProblemModels.Count;

                    reportWriter.WriteLine("Aggregate results");
                    reportWriter.WriteLine("Aggregate time");
                    reportWriter.WriteLine(totalTime);
                    reportWriter.WriteLine("Average error");
                    reportWriter.WriteLine(averageError);
                }
            }
            else
            {
                Environment.Exit(1);
            }

            Environment.Exit(0);
        }
Beispiel #23
0
        public void BruteForce_SingleState_UnsolvableHandling()
        {
            //This puzzle is not invalid yet, but it's going to become invalid real quick
            //I think this is about the only "unsolvable" option for brute force
            Board UnSolvedBoard        = new Board(BoardTest.UnsolvablePuzzle());
            bool  HitExpectedException = false;

            BruteForceSolver Solver = new BruteForceSolver();

            try
            {
                Solver.SingleStateBruteForceSolve(ref UnSolvedBoard);
            }
            catch (Exception e)
            {
                if (e.Message.Equals(BruteForceSolver.UnsolvableBoardmessage))
                {
                    HitExpectedException = true;
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (!HitExpectedException)
                {
                    Assert.Fail("Brute Force failed to hit the expected Unsolvable exception.");
                }
            }


            //And now make sure we fail fast and complain if they give us a board that's already invalid
            UnSolvedBoard          = new Board(BoardTest.UnsolvablePuzzle());
            UnSolvedBoard.Cells[8] = new Cell(5);
            HitExpectedException   = false;

            try
            {
                Solver.SingleStateBruteForceSolve(ref UnSolvedBoard);
            }
            catch (Exception e)
            {
                if (e.Message.Equals(BruteForceSolver.InvalidBoardMessage))
                {
                    HitExpectedException = true;
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (!HitExpectedException)
                {
                    Assert.Fail("Brute Force failed to hit the expected Invalid Board exception.");
                }
            }
        }
Beispiel #24
0
        public void BruteForce_Recursive_SimpleTest()
        {
            //For testing purposes, if we need to zero out a cell, we reassign the value in the list to a new "zero cell"
            //When lists of cells are initialized, if they have values filled in, those values are considered non-changeable
            //which is good, we want that, just for the purposes of fiddling with data for tests, that's less convenient

            bool MultipleSolutionsFound = false;

            //make sure test does nothing on an already-solved board
            List <Cell>      SolvedCells = BoardTest.SolvedSudokuPuzzle1();
            Board            SolvedBoard = new Board(SolvedCells);
            BruteForceSolver Solver      = new BruteForceSolver();

            Solver.RecursiveBruteForceSolve(ref SolvedBoard, ref MultipleSolutionsFound);

            Assert.IsTrue(BoardTest.CellListsAreEqual(SolvedBoard.Cells, SolvedCells),
                          "Brute force solver changed values on an already-solved board");
            Assert.IsFalse(MultipleSolutionsFound,
                           "Recursive Brute force solver said there were multiple solutions on an already-solved board");

            //now let's blank out one value on our board, and see the brute force solver fill it in
            Board MissingOneBoard = new Board(SolvedCells);
            int   OriginalValue   = MissingOneBoard.Cells[8].Value;

            MissingOneBoard.Cells[8] = new Cell(0);
            Solver.RecursiveBruteForceSolve(ref MissingOneBoard, ref MultipleSolutionsFound);

            Assert.IsTrue(MissingOneBoard.Cells[8].Value == OriginalValue,
                          "Brute force solver failed to fill in 1 value missing from completed board");
            Assert.IsFalse(MultipleSolutionsFound,
                           "Recursive Brute force solver said there were multiple solutions on a board missing 1 value");

            //now let's blank out three values in a row on our board, and see the brute force solver fill them in
            //this is an incredibly easy sudoku

            Board MissingThreeBoard = new Board(SolvedCells);
            int   OriginalValue1    = MissingOneBoard.Cells[6].Value;

            MissingOneBoard.Cells[6] = new Cell(0);
            int OriginalValue2 = MissingOneBoard.Cells[7].Value;

            MissingOneBoard.Cells[7] = new Cell(0);
            int OriginalValue3 = MissingOneBoard.Cells[8].Value;

            MissingOneBoard.Cells[8] = new Cell(0);
            Solver.RecursiveBruteForceSolve(ref MissingOneBoard, ref MultipleSolutionsFound);

            Assert.IsTrue(MissingOneBoard.Cells[6].Value == OriginalValue1 &&
                          MissingOneBoard.Cells[7].Value == OriginalValue2 &&
                          MissingOneBoard.Cells[8].Value == OriginalValue3,
                          "Brute force solver failed to fill in 3 values in a row missing from completed board: " +
                          OriginalValue1 + " is now " + MissingOneBoard.Cells[6].Value + ", " +
                          OriginalValue2 + " is now " + MissingOneBoard.Cells[7].Value + ", " +
                          OriginalValue3 + " is now " + MissingOneBoard.Cells[8].Value);
            Assert.IsFalse(MultipleSolutionsFound,
                           "Recursive Brute force solver said there were multiple solutions on a board missing 3 values");


            //Let's blank out three more random cells
            OriginalValue1            = MissingOneBoard.Cells[18].Value;
            MissingOneBoard.Cells[18] = new Cell(0);
            OriginalValue2            = MissingOneBoard.Cells[40].Value;
            MissingOneBoard.Cells[40] = new Cell(0);
            OriginalValue3            = MissingOneBoard.Cells[78].Value;
            MissingOneBoard.Cells[78] = new Cell(0);
            Solver.RecursiveBruteForceSolve(ref MissingOneBoard, ref MultipleSolutionsFound);

            Assert.IsTrue(MissingOneBoard.Cells[18].Value == OriginalValue1 &&
                          MissingOneBoard.Cells[40].Value == OriginalValue2 &&
                          MissingOneBoard.Cells[78].Value == OriginalValue3,
                          "Brute force solver failed to fill in 3 scattered values missing from completed board: " +
                          OriginalValue1 + " is now " + MissingOneBoard.Cells[18].Value + ", " +
                          OriginalValue2 + " is now " + MissingOneBoard.Cells[40].Value + ", " +
                          OriginalValue3 + " is now " + MissingOneBoard.Cells[78].Value);
            Assert.IsFalse(MultipleSolutionsFound,
                           "Recursive Brute force solver said there were multiple solutions on a board missing 3 scattered values");
        }