コード例 #1
0
        static async Task RunOneTimeAsync(CLIOptions options)
        {
            ProblemSolver solver = new ProblemSolver(options.LogProgress);

            using (var apiaryClient = new ApiaryHttpClient())
            {
                Console.WriteLine("Getting problem ...");
                var problemDefinition = await apiaryClient.GetProblemDefinitionAsync();

                Console.WriteLine($"Solving {problemDefinition.Id}");

                Stopwatch sw   = Stopwatch.StartNew();
                string    path = solver.Solve(problemDefinition);
                sw.Stop();
                Console.WriteLine($"Solved [{sw.ElapsedMilliseconds}ms]");
                Console.WriteLine("Posting solution");
                var problemSolution = new ProblemSolutionDto
                {
                    Path = path
                };
                var response = await apiaryClient.PutSolution(problemDefinition, problemSolution);

                Console.WriteLine($"Valid: {(response.Valid ? "yes" : "no")}");
                Console.WriteLine($"In time: {(response.InTime ? "yes" : "no")}");
                if (!string.IsNullOrEmpty(response.Message))
                {
                    Console.WriteLine($"Message: {response.Message}");
                }
            }
        }
コード例 #2
0
        public void BigDataTest()
        {
            var experts = new List <Expert>()
            {
            };

            var projects = new List <Project>()
            {
            };

            for (int i = 0; i < 200; ++i)
            {
                var specializations = new List <bool>();
                var requirements    = new List <int>();

                for (int j = 0; j < 10; ++j)
                {
                    specializations.Add(true);
                    requirements.Add(j);
                }
                experts.Add(new Expert(i, specializations));
                projects.Add(new Project(i, requirements));
            }

            var   solver    = new ProblemSolver(experts, projects);
            Graph graphFlow = solver.Solve();
        }
コード例 #3
0
        public void SolverProblem_BFSFringeOnly1Result_CorrectResult()
        {
            var solver  = new ProblemSolver <ShipProblemData>();
            var summary = solver.SolveProblem(new BFSFringe <ShipProblemData>(), new ShipProblem(), new Config {
                MaxNumberOfResults = 1
            });

            Assert.IsTrue(summary.MaxNumberOfStates == 3);
            Assert.IsTrue(summary.TotalNumberOfStates == 40);

            Assert.IsNotNull(summary);
            Assert.IsTrue(summary.Results.Count == 1);
            Assert.IsTrue(summary.Results[0].Data != null);
            Assert.IsTrue(summary.Results[0].Data.Count == 19);
            Assert.IsTrue(summary.Results[0].Data[0].CurrentPath != null);
            Assert.IsTrue(summary.Results[0].Data[0].CurrentPath.Count == 19);

            Assert.IsTrue(summary.Results[0].Data[0].Ports.All(p => p.Value.Count == 0));
            var pathAsList = summary.Results[0].Data[0].CurrentPath.ToList();
            var lastPort   = pathAsList.Last();

            for (var i = 0; i < pathAsList.Count; ++i)
            {
                Assert.IsTrue(pathAsList[i] == Solutions[lastPort][i]);
            }
        }
コード例 #4
0
        public void CorrectFeaturesSupplYSumTest()
        {
            int     numberOfProjects  = 3;
            int     numberOfExperts   = 3;
            int     numberOfFeatures  = 4;
            Problem problem           = GenerateProblem(numberOfFeatures, numberOfProjects, numberOfExperts);
            double  methodCoefficient = 0;

            ProblemSolver solver = new ProblemSolver(problem, methodCoefficient);

            solver.BuildConnections();
            solver.CreateStackOfFeaturesPopularity();
            solver.CreateStackOfProjectsDifficulty();

            int sum = 0;

            for (int f = 0; f < numberOfFeatures; f++)
            {
                foreach (Expert expert in problem.listExperts)
                {
                    if (expert.HasFeature(f))
                    {
                        sum += 1;
                    }
                }
            }

            Assert.AreEqual(sum, solver._featuresSupplySum);
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: Arlofin/SO_ColourGroups
        static void Main(string[] args)
        {
            var blue   = new Color("B", new[] { 10, 20, 100, 200 }, new Interval(0, 0));
            var red    = new Color("R", new[] { 50, 105, 150 }, new Interval(0, 20));
            var green  = new Color("G", new[] { 80, 110, 250 }, new Interval(0, 25));
            var yellow = new Color("Y", new[] { 42, 62, 82, 102, 122, 142, 162 }, new Interval(0, 25));

            var spec = new ProblemSpecification(new[] { blue, red, green, yellow }, 0.5);

            var groups = ProblemSolver.NaiveSolver(spec);

            Console.WriteLine("*** Color Group Finder ***");
            Console.WriteLine();
            Console.WriteLine("The colors:");
            Console.WriteLine("Blue:   {0}", String.Join(", ", blue.Points));
            Console.WriteLine("Red:    {0}", String.Join(", ", red.Points));
            Console.WriteLine("Green:  {0}", String.Join(", ", green.Points));
            Console.WriteLine("Yellow: {0}", String.Join(", ", yellow.Points));
            Console.WriteLine();
            Console.WriteLine("The distances:");
            Console.WriteLine("Before red:    {0}", red.Distance);
            Console.WriteLine("Before green:  {0}", green.Distance);
            Console.WriteLine("Before yellow: {0}", yellow.Distance);
            Console.WriteLine();
            Console.WriteLine("{0} colors may be skipped.", spec.Colors.Count - ProblemSolver.MinimalNumberOfColors(spec.Colors.Count, spec.Fraction));
            Console.WriteLine();
            Console.WriteLine("The groups:");
            foreach (var group in groups)
            {
                Console.WriteLine(String.Join(", ", group.Elements));
            }
        }
コード例 #6
0
        public void Test_ParamCountThreshold()
        {
            var code = @"
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main() {}
        
        static int Evaluate(params bool[] parameters)
        {
            int x;
            x = 1;
            if (parameters[0])
            {
                if (parameters[20])
                {
                    x = 2;
                }
            }
            return x;
        }
    }
}
";

            var result = ProblemSolver.Run(code);

            Assert.AreEqual(AnalysisType.Static, result.UsedAnalysisType);
        }
コード例 #7
0
        public void SimpleTest()
        {
            var goal = new Board();

            goal.Init();

            var board = goal.Clone();

            //Move blank twice to the right
            Assert.IsTrue(board.Move(Direction.Right));
            Assert.IsTrue(board.Move(Direction.Right));

            Game15Problem problem = new Game15Problem();
            ProblemSolver <Board, SimpleTransition> problemSolver = new ProblemSolver <Board, SimpleTransition>(board, goal, problem);
            var solution = problemSolver.Solve();

            Assert.AreEqual(3, solution.Count);
            Assert.AreEqual(board, solution[0]);

            var middleState = board.Clone();

            Assert.IsTrue(middleState.Move(Direction.Left));
            Assert.AreEqual(middleState, solution[1]);

            Assert.AreEqual(goal, solution[2]);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: RobertFaller/WordAnagram
        static void Main(string[] args)
        {
            System.Console.WriteLine("Please enter a starting word");

            string StartWord = Console.ReadLine().ToLower();

            //string StartWord = "test";

            System.Console.WriteLine("Starting word is:" + StartWord);

            System.Console.WriteLine("Please enter an ending word");

            string EndWord = Console.ReadLine().ToLower();

            //string EndWord = "ping";

            System.Console.WriteLine("Ending word is:" + EndWord);

            System.Console.WriteLine("Loading Data Dictionary");

            int Length = StartWord.Length;

            HashSet <string> Data = ProblemSolver.GetWordList(Length);

            var Result = ProblemSolver.Solver(StartWord, EndWord, Data, Length);

            System.Console.WriteLine("The shortest path from " + StartWord + "to end word " + EndWord + " is " + Result);
        }
コード例 #9
0
        public void Test_ConstantExpression()
        {
            var code = @"
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main() {}
        
        static int Evaluate(params bool[] parameters)
        {
            int x;
            x = 1;
            if (parameters[22])
            {
                x = 2;
                if (parameters[23 - 1])
                {
                    x = 3;
                }
            }
            return x;
        }
    }
}
";

            var result = ProblemSolver.Run(code);

            CollectionAssert.AreEquivalent(new[] { 1, 3 }, result.ReturnValues.ToArray());
        }
コード例 #10
0
        public void Test_NoParams_DynamicAnalysis()
        {
            var code = @"
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main() {}
        
        static int Evaluate(params bool[] parameters)
        {
            int x;
            x = 1;
            return x;
        }
    }
}
";

            var result = ProblemSolver.Run(code, AnalysisType.Dynamic);

            Assert.AreEqual(AnalysisType.Dynamic, result.UsedAnalysisType);
            CollectionAssert.AreEquivalent(new [] { 1 }, result.ReturnValues.ToArray());
        }
コード例 #11
0
        public void Test_NotConstantParameterAccess()
        {
            var code = @"
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main() {}
        
        static int Evaluate(params bool[] parameters)
        {
            int x;
            x = 1;
            if (parameters[22])
            {
                x = 2;
                if (parameters[24 - x])
                {
                    x = 3;
                }
            }
            return x;
        }
    }
}
";

            var result = ProblemSolver.Run(code, dryRun: true);

            Assert.AreEqual(AnalysisType.Dynamic, result.UsedAnalysisType);
        }
コード例 #12
0
ファイル: Form1.cs プロジェクト: mostafin/FuzzyLogic
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                ClearCharts();
                problemSolver = new ProblemSolver(chart4, chart5, chart6);
            }

            try
            {
                results = problemSolver.Solve(Convert.ToDouble(textBoxSpeed.Text), Convert.ToDouble(textBoxTemp.Text));

                textBox3.Text = "Wysokie na poziomie " + results[0].ToString();
                textBox4.Text = "Średnio wysokie na poziomie " + results[1].ToString();
                textBox5.Text = "Średnio wysokie na poziomie " + results[2].ToString();
                textBox6.Text = "Niskie na poziomie " + results[3].ToString();
                textBox1.Text = "Średnio niskie na poziomie " + results[4].ToString();
                textBox2.Text = "Niskie na poziomie " + results[5].ToString();
                textBox7.Text = "Średnio niskie na poziomie " + results[6].ToString();
                textBox8.Text = "Średnie na poziomie " + results[7].ToString();
                textBox9.Text = "Wysokie na poziomie " + results[8].ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("Nie podano parametrów");
            }
        }
コード例 #13
0
        public void Test_AvoiDeadEqualsComparison_StaticAnalysis()
        {
            var code = @"
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main() {}
        
        static int Evaluate(params bool[] parameters)
        {
            int x;
            x = 1;
            if (parameters[0])
            {
                x = 2;
                if (parameters[0] == true && parameters[0] == false)
                {
                    x = 3;
                }
            }
            return x;
        }
    }
}
";

            var result = ProblemSolver.Run(code, AnalysisType.Static);

            Assert.AreEqual(AnalysisType.Static, result.UsedAnalysisType);
            CollectionAssert.AreEquivalent(new[] { 1, 2 }, result.ReturnValues.ToArray());
        }
コード例 #14
0
        public void SolverProblem_BFSFringeWithoutLastPort_CorrectResult()
        {
            var solver  = new ProblemSolver <ShipProblemData>();
            var summary = solver.SolveProblem(new BFSFringe <ShipProblemData>(), new ShipProblem(true));

            Assert.IsTrue(summary.MaxNumberOfStates == 9);
            Assert.IsTrue(summary.TotalNumberOfStates == 112);

            Assert.IsNotNull(summary);
            Assert.IsTrue(summary.Results.Count == 3);
            foreach (var res in summary.Results)
            {
                Assert.IsTrue(res.Data != null);
                Assert.IsTrue(res.Data.Count == 19);
                Assert.IsTrue(res.Data[0].CurrentPath != null);
                Assert.IsTrue(res.Data[0].CurrentPath.Count == 19);
                Assert.IsTrue(res.Data[0].Ports.All(p => p.Value.Count == 0));

                var pathAsList = res.Data[0].CurrentPath.ToList();
                var lastPort   = pathAsList.Last();
                for (var i = 0; i < pathAsList.Count; ++i)
                {
                    Assert.IsTrue(pathAsList[i] == Solutions[lastPort][i]);
                }
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            Experts  = new List <Expert>();
            Projects = new List <Project>();
            if (args.Length == 0)
            {
                Console.WriteLine("Nie podano argumentu");
                System.Environment.Exit(1);
            }
            FillCollections(args[0]);
            Console.WriteLine("Program wczytał dane z pliku");

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

            stopwatch.Start();
            var solver = new ProblemSolver(Experts, Projects);

            solver.Solve();
            stopwatch.Stop();

            Console.WriteLine();
            Console.WriteLine("Czas wykonania:");
            Console.WriteLine(stopwatch.Elapsed.TotalSeconds + "s");
            Console.WriteLine();
        }
コード例 #16
0
        public void NoExpertsTest()
        {
            var experts = new List <Expert>()
            {
            };
            var projects = new List <Project>()
            {
                new Project(0, new List <int> {
                    1, 0, 1
                }),
                new Project(1, new List <int> {
                    1, 0, 1
                }),
            };

            var   solver    = new ProblemSolver(experts, projects);
            Graph graphFlow = solver.Solve();

            if (graphFlow == null)
            {
                return;
            }

            GraphExport ge = new GraphExport();

            ge.Export(graphFlow, null, "Graph");
        }
コード例 #17
0
        public void ProblemSolverCoefficient2Test()
        {
            Problem       problem           = GenerateProblem(7);
            double        methodCoefficient = 3;
            ProblemSolver solver            = new ProblemSolver(problem, methodCoefficient);

            Assert.AreEqual(1, solver.MethodCoefficient);
        }
コード例 #18
0
        public void ProblemSolverCoefficient1Test()
        {
            Problem       problem           = GenerateProblem(1);
            double        methodCoefficient = -200;
            ProblemSolver solver            = new ProblemSolver(problem, methodCoefficient);

            Assert.AreEqual(0, solver.MethodCoefficient);
        }
コード例 #19
0
        static async Task RunMineAsync(CLIOptions options)
        {
            var solver = new ProblemSolver(options.LogProgress);

            using (var apiaryClient = new ApiaryHttpClient(options.SaveApiCalls))
                using (var solutionService = options.SaveSolutions ? new ProblemSolutionService() : null)
                {
                    int       fails             = 0;
                    const int MaxFailInRowCount = 3;
                    DateTime  time = DateTime.MinValue;
                    while (true)
                    {
                        time = await ThrottleAsync(time, ApiaryHttpClient.RequiredDelay);

                        var problemDefinition = await apiaryClient.GetProblemDefinitionAsync();

                        Console.WriteLine($"Solving {problemDefinition.Id}");
                        Stopwatch sw   = Stopwatch.StartNew();
                        string    path = solver.Solve(problemDefinition);
                        sw.Stop();
                        Console.WriteLine($"Solved [{sw.ElapsedMilliseconds}ms]");
                        time = await ThrottleAsync(time, ApiaryHttpClient.RequiredDelay);

                        var problemSolution = new ProblemSolutionDto
                        {
                            Path = path
                        };
                        var response = await apiaryClient.PutSolution(problemDefinition, problemSolution);

                        if (!response.Valid || !response.InTime)
                        {
                            var ex = new Exception($"Invalid solution for problem={problemDefinition.Id}");
                            ex.Data[nameof(ProblemSolutionDto)]   = problemSolution;
                            ex.Data[nameof(ProblemDefinitionDto)] = problemDefinition;
                            throw ex;
                        }

                        if (options.SaveSolutions)
                        {
                            var added = await solutionService?.RegisterSolutionAsync(problemDefinition.Id, path);

                            if (!added)
                            {
                                fails++;
                            }
                            else
                            {
                                fails = 0;
                            }

                            if (fails == MaxFailInRowCount)
                            {
                                break;
                            }
                        }
                    }
                }
        }
コード例 #20
0
        public void DTest()
        {
            var problem  = ProblemBuilder.Build(File.ReadAllLines(@"..\..\..\Resources\d_metropolis.in"));
            var solution = ProblemSolver.Solve(problem);

            Assert.NotNull(solution);
            Trace.WriteLine(solution.GetTotalScore(problem.Bonus).ToString());
            Trace.WriteLine(solution.ToString());
        }
コード例 #21
0
        private void problemSolver(Exception ex)
        {
            var found = new ProblemSolver(ex).FMsg;

            if (found != null)
            {
                _ActualTask.Log.LogError(found);
            }
        }
コード例 #22
0
        public void GetSolution()
        {
            var asd   = problem.ToString();
            var contr = new ProblemsController();


            var solver    = new ProblemSolver <ExpertChoicesModels.Problem, ExpertChoicesModels.Expert, ExpertChoicesModels.Expert, ExpertChoicesModels.Alternative>(problem);
            var solution2 = solver.SolveTheProblem();
        }
コード例 #23
0
        public void BTest()
        {
            var problem  = ProblemBuilder.Build(File.ReadAllLines(@"..\..\..\Resources\b_should_be_easy.in"));
            var solution = ProblemSolver.Solve(problem);

            Assert.NotNull(solution);
            Trace.WriteLine(solution.GetTotalScore(problem.Bonus).ToString());
            Trace.WriteLine($"Missed rides: {string.Join(" ", solution.GetMissedRides())}");
            Trace.WriteLine(solution.ToString());
        }
コード例 #24
0
        public void BuildConnectionsTest()
        {
            Problem       problem           = GenerateProblem(4);
            double        methodCoefficient = 0;
            ProblemSolver solver            = new ProblemSolver(problem, methodCoefficient);

            solver.BuildConnections();
            Assert.IsNotNull(solver.ListEdges);
            Assert.IsTrue(solver.ListEdges.Count > 0);
        }
コード例 #25
0
        public void OnlyTwo()
        {
            int           upperBound    = 2;
            int           expected      = 2;
            ProblemSolver problemSolver = new ProblemSolver();

            int actual = problemSolver.SumEvenOfEvenFibunacciNumbersUpTo(upperBound);

            Assert.AreEqual(expected, actual);
        }
コード例 #26
0
        static void Main(string[] args)
        {
            int           maximumFibunacciNumber = 4000000;
            ProblemSolver fibunacci = new ProblemSolver();

            var sumEvenFibunacciNumbers = fibunacci.SumEvenOfEvenFibunacciNumbersUpTo(maximumFibunacciNumber);

            Console.WriteLine("Sum: " + sumEvenFibunacciNumbers);
            Console.ReadKey();
        }
コード例 #27
0
ファイル: SVM.cs プロジェクト: douglas125/OpenCLTemplate
        /// <summary>Trains current SVM</summary>
        public void Train()
        {
            //if (alphaList == null || alphaList.Count != TrainingSet.getN) initializeWithZeros();
            initializeWithZeros();

            PreComputeKernels();

            //Solves SMO
            ProblemSolver.solveSMOStartingFromPreviousSolution(this);
        }
コード例 #28
0
        public void Test_Sample2()
        {
            var code = @"
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main()
        {
            // выведет 1
            Console.WriteLine( Evaluate(false, false, false, false) );

            // выведет 6
            Console.WriteLine( Evaluate(false, false, false, true) );

            //...
        }

        static int Evaluate(params bool[] parameters)
        {
            int x;
            x = 1;
            if (parameters[0])
            {
                x = 2;
                if (parameters[1])
                {
                    x = 3;
                }
                x = 4;
                if (parameters[2])
                {
                    if (parameters[3])
                    {
                        x = 6;
                    }
                    if (parameters[4])
                    {
                        x = 5;
                    }
                }
            }

            return x;
        }
    }
}
";

            var result = ProblemSolver.Run(code);

            CollectionAssert.AreEquivalent(new[] { 1, 4, 5, 6 }, result.ReturnValues.ToArray());
        }
コード例 #29
0
        public void SolverProblem_DFSFringeOverrideInitialState_CorrectResult()
        {
            var solver = new ProblemSolver <ShipProblemData>();

            //This problem is a sub-problem of the original problem
            var myData = new ShipProblemData();

            myData.CurrentPath.Push(Ports.Port1);

            var book = new Stack <string>();

            book.Push(Ports.Port2);
            book.Push(Ports.Port1);
            book.Push(Ports.Port3);
            myData.Ports[Ports.Port1] = book;

            book = new Stack <string>();

            book.Push(Ports.Port3);
            book.Push(Ports.Port1);
            book.Push(Ports.Port1);
            myData.Ports[Ports.Port2] = book;

            book = new Stack <string>();

            book.Push(Ports.Port2);
            book.Push(Ports.Port3);
            book.Push(Ports.Port2);
            myData.Ports[Ports.Port3] = book;

            var summary = solver.SolveProblem(new DFSFringe <ShipProblemData>(), new ShipProblem(),
                                              new Config {
                DataForInitialState = myData
            });

            Assert.IsTrue(summary.MaxNumberOfStates == 3);
            Assert.IsTrue(summary.TotalNumberOfStates == 18);

            Assert.IsNotNull(summary);
            Assert.IsTrue(summary.Results.Count == 1);
            Assert.IsTrue(summary.Results[0].Data != null);
            Assert.IsTrue(summary.Results[0].Data.Count == 10);
            Assert.IsTrue(summary.Results[0].Data[0].CurrentPath != null);
            Assert.IsTrue(summary.Results[0].Data[0].CurrentPath.Count == 10);

            Assert.IsTrue(summary.Results[0].Data[0].Ports.All(p => p.Value.Count == 0));
            var pathAsList = summary.Results[0].Data[0].CurrentPath.ToList();
            var lastPort   = pathAsList.Last();

            for (var i = 0; i < pathAsList.Count; ++i)
            {
                Assert.IsTrue(pathAsList[i] == Solutions[lastPort][i]);
            }
        }
コード例 #30
0
ファイル: SVM.cs プロジェクト: douglas125/OpenCLTemplate
 /// <summary>Classifies a training unit with a float. The bigger, the more positive the sample. Values greater than zero
 /// are assumed to be positive samples</summary>
 /// <param name="Sample">Sample to be classified</param>
 public float ClassificationValue(TrainingUnit Sample)
 {
     if (OpenCLTemplate.CLCalc.CLAcceleration == OpenCLTemplate.CLCalc.CLAccelerationType.UsingCL)
     {
         return(CLpredictOutput(this, Sample));
     }
     else
     {
         return(ProblemSolver.predictOutput(this, Sample));
     }
 }