Example #1
0
        public void NoDenominationsProduceNoSolution()
        {
            var strategy = new GreedyStrategy();
            var result   = strategy.Solve(1, Array.Empty <int>());

            Assert.That(result, Is.Not.Null, "The result should have been returned.");
            Assert.That(result, Is.Empty, "The result should not contain any denominations.");
        }
Example #2
0
        public void NoValueProducesNoSolution(int value)
        {
            var strategy = new GreedyStrategy();
            var result   = strategy.Solve(value, new[] { 1, 5, 10, 25 });

            Assert.That(result, Is.Not.Null, "The result should have been returned.");
            Assert.That(result, Is.Empty, "The result should not contain any denominations.");
        }
Example #3
0
        public void UnsolvableCombinationsProduceNoSolution(int value,
                                                            int[] denominations)
        {
            var strategy = new GreedyStrategy();
            var result   = strategy.Solve(value, denominations);

            Assert.That(result, Is.Not.Null, "The result should have been returned.");
            Assert.That(result, Is.Empty, "The result should not contain any denominations.");
        }
Example #4
0
        public void LocalMaximumCasesProduceIncorrectSolutions(int value,
                                                               int[] denominations,
                                                               IReadOnlyList <CoinUse> expectedResult)
        {
            var strategy = new GreedyStrategy();
            var result   = strategy.Solve(value, denominations);

            Assert.That(result, Is.Not.Null, "The result should have been returned.");
            Assert.That(result.IsEquivalentTo(expectedResult), Is.True, "The result should have matched the expectation.");
        }
Example #5
0
        static void Main(string[] args)
        {
            if (args.Contains("-h"))
            {
                HandleHelp();
            }


            var file    = args[0];
            var timeout = int.Parse(args[1]);
            var runs    = int.Parse(args[2]);
            var output  = args.Count() == 4
                ? args[3]
                : string.Empty;

            System.Console.WriteLine($"Input params:");
            System.Console.WriteLine($"File: {file}");
            System.Console.WriteLine($"Timeout: {timeout}[s]");
            System.Console.WriteLine($"Runs: {runs}");
            System.Console.WriteLine($"Output: {output}");


            System.Console.WriteLine($"Reading data from input file");
            var data = ReadData(file);

            System.Console.WriteLine("OK");

            var randomResults   = new List <QapResult <int> >();
            var steepestResults = new List <QapResult <int> >();
            var greedyResults   = new List <QapResult <int> >();


            for (var currentRun = 1; currentRun <= runs; currentRun++)
            {
                System.Console.WriteLine();
                System.Console.WriteLine($"### Run: {currentRun} ###");

                var initialPermutation = QapMath.Permutate(QapMath.Range(1, data.MatricesSize));
                System.Console.WriteLine($"Initial permutation: {string.Join(",",initialPermutation)}");

                var cancelationToken = new CancelationToken();

                var randomStrategy   = new RandomStrategy();
                var steepestStrategy = new SteepestStrategy();
                var greedyStrategy   = new GreedyStrategy();

                Func <IEnumerable <int>, float> scoringFunction = (x) => Score(data, x);

                var timer = new Timer(timeout * millisecondsInSeconds);
                timer.Elapsed += (sender, eargs) => cancelationToken.Cancel();

                System.Console.WriteLine("Starting tasks");
                var randomStartegyTask   = Task.Run(() => randomStrategy.SearchBest(scoringFunction, initialPermutation, cancelationToken));
                var steepestStrategyTask = Task.Run(() => randomStrategy.SearchBest(scoringFunction, initialPermutation, cancelationToken));
                var greedyStrategyTask   = Task.Run(() => greedyStrategy.SearchBest(scoringFunction, initialPermutation, cancelationToken));

                System.Console.WriteLine("OK");

                System.Console.WriteLine("Starting timer");
                timer.Start();
                System.Console.WriteLine("OK");

                System.Console.WriteLine("Awaiting tasks to finish");
                Task.WaitAll(new [] { randomStartegyTask, steepestStrategyTask, greedyStrategyTask });
                System.Console.WriteLine("OK");

                System.Console.WriteLine("Collecting results");
                QapResult <int> randomResult   = randomStartegyTask.Result as QapResult <int> ?? null;
                QapResult <int> steepestResult = steepestStrategyTask.Result as QapResult <int> ?? null;
                QapResult <int> greedyResult   = greedyStrategyTask.Result as QapResult <int> ?? null;

                randomResults.Add(randomResult);
                steepestResults.Add(steepestResult);
                greedyResults.Add(greedyResult);

                System.Console.WriteLine("OK");

                System.Console.WriteLine();
                System.Console.WriteLine($"# Results for run: {currentRun}");
                System.Console.WriteLine("Results in format <foundIntime>:<solution>/<ofTotalSeen>:<steps>:<score>:<Permutation>");
                System.Console.WriteLine($"Best random: {randomResult.FoundIn.TotalMilliseconds}:{randomResult.SeenAsSolutionNumber}/{randomResult.TotalSolutionsSeen}:{randomResult.Steps}:{randomResult.Score}:[{String.Join(",",randomResult.Solution)}]");
                System.Console.WriteLine($"Best steepest: {steepestResult.FoundIn.TotalMilliseconds}:{steepestResult.SeenAsSolutionNumber}/{steepestResult.TotalSolutionsSeen}:{steepestResult.Steps}:{steepestResult.Score}:[{String.Join(",",steepestResult.Solution)}]");
                System.Console.WriteLine($"Best greedy: {greedyResult.FoundIn.TotalMilliseconds}:{greedyResult.SeenAsSolutionNumber}/{greedyResult.TotalSolutionsSeen}:{greedyResult.Steps}:{greedyResult.Score}:[{String.Join(",",greedyResult.Solution)}]");
            }

            if (!string.IsNullOrEmpty(output))
            {
                using (var writer = new StreamWriter(File.OpenWrite(output)))
                {
                    writer.WriteLine("algorithm,time,solutionNr,totalSolutions,steps,score,solution");

                    foreach (var solution in randomResults)
                    {
                        writer.WriteLine($"random,{solution.ToCsvLine()}");
                    }
                    foreach (var solution in steepestResults)
                    {
                        writer.WriteLine($"steepest,{solution.ToCsvLine()}");
                    }
                    foreach (var solution in greedyResults)
                    {
                        writer.WriteLine($"greedy,{solution.ToCsvLine()}");
                    }
                }
            }
        }