public void test_that_given_a_repository_with_many_changesets_the_latest_changeset_is_returned_by_get()
        {
            // arrange
            var changes = new List<SpeakerChange>
                              {
                                  new SpeakerChange() { Version = 1 },
                                  new SpeakerChange() { Version = 1 },
                                  new SpeakerChange() { Version = 2 }
                              };
            var mock = new Mock<ISpeakerChangeRepository>();
            mock.Setup(m => m.GetLatest()).Returns(() =>
                                                    {
                                                        int latestVersion = changes.Max(c => c.Version);
                                                        return changes.Where(c => c.Version == latestVersion).ToList();
                                                    });

            _container.Bind<ISpeakerChangeRepository>().ToConstant(mock.Object);

            // act
            var controller = (SpeakerChangeController)_container.Get<IHttpController>("SpeakerChange", new IParameter[0]);
            var result = controller.Get();

            // assert
            Assert.AreNotEqual(0, result.Count());
        }
        public void test_that_get_returns_only_the_latest_changeset()
        {
            // arrange
            var changes = new List<SessionChange>
                               {
                                   new SessionChange {ActionType = ChangeAction.Add, SessionId = 123, Version = 1},
                                   new SessionChange
                                       {
                                           ActionType = ChangeAction.Modify,
                                           SessionId = 124,
                                           Key = "Title",
                                           Value = "new Title",
                                           Version = 1
                                       },
                                   new SessionChange {ActionType = ChangeAction.Delete, SessionId = 125, Version = 2},
                               };

            var mock = new Mock<ISessionChangeRepository>();
            mock.Setup(m => m.GetLatest()).Returns(() =>
                                                       {
                                                           int latestVersion = changes.Max(s => s.Version);
                                                           return changes.Where(sc => sc.Version == latestVersion).ToList();
                                                       });
            _container.Bind<ISessionChangeRepository>().ToConstant(mock.Object);

            // act
            var controller = (SessionChangeController)_container.Get<IHttpController>("SessionChange", new IParameter[0]);
            var result = controller.Get();

            // assert
            Assert.AreEqual(1, result.Count());
        }
        private static void PrintSchedule(List<Employee> employees, List<Duty> duties)
        {
            var maxNameLength = employees.Max(x => x.Name.Length);

            duties = duties.OrderBy(x => x.Timeslot).ToList();

            Debug.Write(new string(' ', maxNameLength + Padding));
            Debug.Write(String.Join("  ", duties.Select(x => x.Timeslot)));
            Debug.WriteLine("");
            foreach (var employee in employees)
            {
                Debug.Write(employee.Name.PadRight(maxNameLength + Padding));

                foreach (var duty in duties)
                {
                    if (duty.Employee.Equals(employee))
                    {
                        Debug.Write("X");
                    }
                    else
                    {
                        Debug.Write(" ");
                    }
                    Debug.Write("  ");
                }

                Debug.Write("    ");
                PrintStatistics(employee, duties.Where(x => Equals(x.Employee, employee)).ToList());

                Debug.WriteLine("");
            }
        }
Example #4
0
        public void AllComputationsOfMinMaxTaskSolverAreCorrect()
        {
            var numbersCount = 1000*1000;
            var threadsCount = 10;

            var formatter = new BinaryFormatter();
            var rand = new Random();

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var numbers = new List<int>(numbersCount);
            for (var i = 0; i < numbersCount; i++)
            {
                numbers.Add(rand.Next(int.MinValue, int.MaxValue));
            }
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + numbersCount + " numbers generated ");

            var expectedMinimum = numbers.Min();
            var expectedMaximum = numbers.Max();
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + " expected results found");

            var problem = new MmProblem(numbers);
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + "problem created ");

            byte[] problemData;
            using (var memoryStream = new MemoryStream())
            {
                formatter.Serialize(memoryStream, problem);
                problemData = memoryStream.ToArray();
            }
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + "problem serialized");

            var taskSolver = new MmTaskSolver(problemData);
            var partialProblemsData = taskSolver.DivideProblem(threadsCount);
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + "problem divided; threadsCount=" +
                            threadsCount);

            var partialSolutionsData = new List<byte[]>(partialProblemsData.Length);
            foreach (var partialProblemData in partialProblemsData)
            {
                var partialSolutionData = taskSolver.Solve(partialProblemData, new TimeSpan());
                partialSolutionsData.Add(partialSolutionData);
            }
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + "partial solutions solved");

            var finalSolutionData = taskSolver.MergeSolution(partialSolutionsData.ToArray());
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + "problems merged");

            using (var memoryStream = new MemoryStream(finalSolutionData))
            {
                var finalSolution = (MmSolution) formatter.Deserialize(memoryStream);
                Assert.AreEqual(finalSolution.Min, expectedMinimum);
                Assert.AreEqual(finalSolution.Max, expectedMaximum);
            }
            Debug.WriteLine(stopwatch.ElapsedMilliseconds/1000.0 + ": " + "final solution deserialized");

            stopwatch.Stop();
        }
        public ProductControllerTest()
        {
            // create some mock products to play with
            IList<Product> products = new List<Product>
            {
            new Product { ProductId = 1, ProductName = "Television",
                ProductDescription = "Sony", Price = 25000 },
            new Product { ProductId = 2, ProductName = "Computer",
                ProductDescription = "Dell", Price = 20000 },
            new Product { ProductId = 4, ProductName = "Table",
                ProductDescription = "Wooden", Price = 600 }
            };

            // Mock the Products Repository using Moq
            Mock<IProductRepository> mockProductRepository = new Mock<IProductRepository>();

            // Return all the products
            mockProductRepository.Setup(mr => mr.FindAll()).Returns(products);

            // return a product by Id

            mockProductRepository.Setup(mr => mr.FindById(It.IsAny<int>())).Returns((int i) => products.Where(x => x.ProductId == i).Single());

            // return a product by Name
            mockProductRepository.Setup(mr => mr.FindByName(It.IsAny<string>())).Returns((string s) => products.Where(x => x.ProductName == s).Single());

            // Allows us to test saving a product
            mockProductRepository.Setup(mr => mr.Save(It.IsAny<Product>())).Returns(
               (Product target) =>
               {
                   if (target.ProductId.Equals(default(int)))
                   {
                       target.ProductId = products.Max(q => q.ProductId) + 1;
                       //target.ProductId = products.Count() + 1;
                       products.Add(target);
                   }
                   else
                   {
                       var original = products.Where(q => q.ProductId == target.ProductId).SingleOrDefault();

                       if (original != null)
                       {
                           return false;
                       }

                       products.Add(target);
                   }

                   return true;
               });

            // Complete the setup of our Mock Product Repository
            this.MockProductsRepository = mockProductRepository.Object;
        }
        public void GenericComparerAsIComparer()
        {
            List<int> ints = new List<int>(new[] { 10, 5, 2, 23, 7, 5, 3, 45, 23, 64, 25 });

            ints.Sort(new GenericComparer<int>());

            Assert.AreEqual(ints.Min(), ints.First());
            Assert.AreEqual(ints.Max(), ints.Last());

            ints.Sort(new GenericComparer<int>((i, i1) => Math.Sin(i) > Math.Sin(i1) ? -1 : Math.Sin(i) < Math.Sin(i1) ? 1 : 0));

            Assert.AreEqual(64, ints.First());
            Assert.AreEqual(5, ints.Last());
        }
 public void TestMemory()
 {
     Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
     long initial = currentProcess.WorkingSet64;
     List<long> measurements = new List<long>() { initial };
     List<Model> models = new List<Model>();
     for (var i = 0; i < 15; i++)
     {
         models.Add(Load());
         measurements.Add(currentProcess.WorkingSet64);
     }
     var peak = currentProcess.PeakWorkingSet64;
     var min = measurements.Min();
     var max = measurements.Max();
     var final = currentProcess.WorkingSet64;
 }
Example #8
0
        public void TestMethod1()
        {
            int lenght = 5;
            string vs = "1 2 4 4 5";

            int[] values = new int[lenght];

            var tab = vs.Split(' ');
            for (int i = 0; i < tab.Length; i++)
            {
                var v = tab[i];
                values[i] = int.Parse(tab[i]);
            }

            int result = 0;
            int delta = 0;
            int refPos = 0;

            List<Element> sommets = new List<Element>();
            for (int i = 0; i < lenght; i++)
            {
                if (IsSommet(i, values))
                {

                    if (sommets.Count==0 || sommets[sommets.Count - 1].Value < values[i])
                    {
                        sommets.Add(new Element(i, 0, values[i]));
                    }
                }
                else
                {
                    int value = values[i];
                    sommets.ForEach(k =>
                    {
                        if (k.Value - value > k.Delta)
                        {
                            k.Delta = k.Value - value;
                        }
                    });
                }
            }

            if(sommets.Count>0)
                result = -sommets.Max(s => s.Delta);

               Assert.AreEqual(0,result);
        }
        public void RollBetweenOneAndTwelve()
        {
            var dice = new MonopolyDice();
            var rolls = new List<Int32>();

            for (var i = 0; i < 1000000; i++)
            {
                dice.RollTwoDice();
                rolls.Add(dice.Value);
            }

            var max = rolls.Max();
            var min = rolls.Min();

            Assert.IsTrue(min > 0);
            Assert.IsTrue(max <= 12);
        }
Example #10
0
        public void CompareTo_TestWithListOfMinAndMax()
        {
            List<RoadType> MinMaxList = new List<RoadType>();

            MinMaxList.Add(new RoadType("Motorvej", 100));
            MinMaxList.Add(new RoadType("MiscVej", 60));
            MinMaxList.Add(new RoadType("VillaVej", 20));
            MinMaxList.Add(new RoadType("MotorTrafikVej", 90));
            MinMaxList.Add(new RoadType("Racerbane", 250));

            RoadType min = MinMaxList.Min();
            RoadType max = MinMaxList.Max();

            Assert.AreSame(min, MinMaxList[2]);
            Assert.AreSame(max, MinMaxList[4]);
            
        }
        public void MaxTest()
        {
            List<int> posIntList = new List<int>();
            List<int> intList = new List<int>();
            List<decimal> posDecimalList = new List<decimal>();
            List<decimal> decimalList = new List<decimal>();
            int sign = -1;

            for (int i = 0; i < 10; i++)
            {
                posIntList.Add(i + 1);
                intList.Add((i + 1) * sign);
                posDecimalList.Add((i + 1) / 10m);
                decimalList.Add(((i + 1) / 10m) * sign);
                sign *= -1;
            }

            Assert.AreEqual(10, posIntList.Max());
            Assert.AreEqual(10, intList.Max());
            Assert.AreEqual(1.0m, posDecimalList.Max());
            Assert.AreEqual(1.0m, decimalList.Max());
        }
Example #12
0
        static void CrudTest(ISimpleEmployeeRepository repo)
        {
            s_DataSource.Sql(@"DELETE FROM Sales.Customer;DELETE FROM HR.Employee;").Execute();

            //actual
            var spans = new List<double>(Iterations);
            for (var i = 0; i < Iterations; i++)
            {
                var sw = Stopwatch.StartNew();
                CrudTestCore(repo);
                sw.Stop();
                spans.Add(sw.Elapsed.TotalMilliseconds);
            }
            Trace.WriteLine("Run Duration: " + spans.Average().ToString("N2") + " ms per iteration. Min: " + spans.Min().ToString("N2") + " ms. Max: " + spans.Max().ToString("N2") + " ms.");

            Trace.WriteLine("");
            Trace.WriteLine("");
            //foreach (var span in spans)
            //    Trace.WriteLine("    " + span.ToString("N2"));

            if (DiscardHighLow && Iterations > 10)
            {
                //Remove the highest and lowest two to reduce OS effects
                spans.Remove(spans.Max());
                spans.Remove(spans.Max());
                spans.Remove(spans.Min());
                spans.Remove(spans.Min());
            }

            Trace.WriteLine("Run Duration: " + spans.Average().ToString("N2") + " ms per iteration. Min: " + spans.Min().ToString("N2") + " ms. Max: " + spans.Max().ToString("N2") + " ms.");

            long frequency = Stopwatch.Frequency;
            Trace.WriteLine($"  Timer frequency in ticks per second = {frequency}");
            long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
            Trace.WriteLine($"  Timer is accurate within {nanosecPerTick} nanoseconds");
        }
        public void GenerateUniqueId()
        {
            List<string> list = new List<string>();
            for (int i = 0; i < 100; i++)
            {
                list.Add(DataUtils.GenerateUniqueId());
            }

            int maxLength = list.Max(str => str.Length);
            int minLength = list.Min(str => str.Length);
            int negVals = list.Where(str => str.StartsWith("-")).Count();
            this.TestContext.WriteLine("Min Length: {0}, Max: {1}, Neg: {2}", minLength, maxLength, negVals);

            Assert.IsTrue(list.Distinct().Count() == 100, "Didn't create 100 unique entries");
        }
Example #14
0
        public void Max_abnormal()
        {
            // arrange
            List<int> listInt = new List<int>();
            Func<int, int> func = null;

            // act and assert
            try
            {
                listInt.Max(func);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is ArgumentNullException);
            }
            try
            {
                listInt.Max(x => x);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
            }
        }
        public async Task PerfomanceCreateTest()
        {
            System.Diagnostics.Debug.Print("Start " + DateTime.Now.ToShortTimeString());

            Stopwatch stopwatch = new Stopwatch();
            var watch = new List<TimeSpan>();

            System.Linq.Enumerable.Range(0, 1000).ToList().ForEach(r => {
                stopwatch.Start();
                PostTest();

                stopwatch.Stop();
                watch.Add(stopwatch.Elapsed);
                stopwatch.Reset();
            });

            var avg = watch.Average(r => r.Milliseconds);
            var min = watch.Min(r => r.Milliseconds);
            var max = watch.Max(r => r.Milliseconds);

            System.Diagnostics.Debug.Print("avg: {0}, min: {1}, max: {2} ", avg, min, max);
            System.Diagnostics.Debug.Print("End " + DateTime.Now.ToShortTimeString());
        }
        public void ListExtensions_Max_ReturnsMaxValue()
        {
            var list = new List<Int32>() { 4, 5, 6, 99, 10, 1, 12, 45 };

            var result = list.Max();

            TheResultingValue(result).ShouldBe(99);
        }
Example #17
0
        public void Test_MaxOrMinValue()
        {
            var u1 = new User { Name = "AB", Email = "234" };
            var u2 = new User { Name = "BC", Email = "123" };
            var list = new List<User> { u1, u2 };
            Assert.AreEqual(u1.Name, list.Min(u => u.Name)); // User需要继承IComparable<User>接口
            Assert.AreEqual(u2.Name, list.Max(u => u.Name));
            Assert.AreEqual(u2.Email, list.Min(u => u.Email));
            Assert.AreEqual(u1.Email, list.Max(u => u.Email));

            Assert.AreEqual(u1.Name, list.MinBy(u => u.Name).Name); // User不需要继承IComparable接口即可实现
            Assert.AreEqual(u2.Name, list.MaxBy(u => u.Name).Name);
            Assert.AreEqual(u2.Email, list.MinBy(u => u.Email).Email);
            Assert.AreEqual(u1.Email, list.MaxBy(u => u.Email).Email);

            var list2 = new List<int> { 1, 2, 3 };
            Assert.AreEqual(1, list2.Min());
            Assert.AreEqual(3, list2.Max());
        }
Example #18
0
        public string Algorithm_2(bool is_mess_acyclic_show, bool is_mess_queue_show)
        {
            idListAlgorithm.Clear();
            string str2 = "[Алгоритм №2] Вершина (Різниця між Тпс і Трс):  ";
            if (GraphIsAcyclic(is_mess_acyclic_show))
            {
                string str = "Проміжкові дані дані\n";
                int n = TopList.Count;

                List<int> Tkri = new List<int>();

                for (int i = 0; i < TopList.Count; i++)
                {
                    NodeIsAcyclic(i, 2, false);
                    Tkri.Add(CriticalPath(i, 3));
                }

                int Tkr = Tkri.Max();
                str += "Tкрг = " + Tkr;

                Dictionary<int, int> node_alg2 = new Dictionary<int, int>();

                int difference = 0;
                int Trs, Tps;
                for (int i = 0; i < TopList.Count; i++)
                {
                    Trs = CriticalPath(i, 2);
                    Tps = Tkr - Tkri[i];
                    difference = Tps - Trs;
                    node_alg2.Add(i, difference);
                    str += "\ni = " + TopList[i].id + ";\tТкр[i] = Tпс[i] (" + Tkr + " - " + Tkri[i] + ") - Трс[i] (" + Trs + ") = " + difference;
                }

                node_alg2 = node_alg2.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
                str += "\n\nРЕЗУЛЬТАТ\nВершина (Різниця між Тпс і Трс)\n";
                foreach (var n_c in node_alg2)
                {
                    idListAlgorithm.Add(n_c.Key);
                    str += TopList[n_c.Key].id + " (" + n_c.Value + ")" + "\n";
                    str2 += TopList[n_c.Key].id + " (" + n_c.Value + ")" + ",  ";
                }
                if (is_mess_queue_show)
                    MessageBox.Show(str, "Алгоритм 2");
            }
            else
                MessageBox.Show("Алгоритм неможливо застосувати, якщо граф має цикли");

            return str2;
        }
        public void ListExtensions_Max_ThrowsExceptionIfListIsEmpty()
        {
            var list = new List<Int32>();

            list.Max();
        }
Example #20
0
        public void Max()
        {
            // arrange
            List<int> listInt = new List<int>() { 1, 2, 3 };
            List<long> listlong = new List<long>() { 1, 2, 3 };
            List<double> listdouble = new List<double>() { 1d, 2d, 3d };
            List<decimal> listdecimal = new List<decimal>() {
                new decimal(1d),
                new decimal(2d),
                new decimal(3d)
            };

            // act
            double actualInt = listInt.Max(x => x);
            double actuallong = listlong.Max(x => x);
            double actualdouble = listdouble.Max(x => x);
            decimal actualdecimal = listdecimal.Max(x => x);

            // assert
            Assert.AreEqual(3, actualInt, 0);
            Assert.AreEqual(3, actuallong, 0);
            Assert.AreEqual(3d, actualdouble, 0);
            Assert.AreEqual(3, actualdecimal);
        }
        public void GetCommandLines_ManyTestsWithSuites_BreaksUpLongCommandLinesCorrectly()
        {
            List<string> allTests = new List<string>();
            List<string> testsToExecute = new List<string>();
            for (int i = 0; i < 1000; i++)
            {
                allTests.Add("MyTestSuite" + i + ".MyTest");
                testsToExecute.Add("MyTestSuite" + i + ".MyTest");
                allTests.Add("MyTestSuite" + i + ".MyTest2");
            }
            testsToExecute.Add("MyTestSuite1.MyTest2");
            testsToExecute.Add("MyTestSuite5.MyTest2");

            IEnumerable<Model.TestCase> allTestCases = allTests.Select(TestDataCreator.ToTestCase).ToList();
            IEnumerable<Model.TestCase> testCases = testsToExecute.Select(TestDataCreator.ToTestCase).ToList();

            List<CommandLineGenerator.Args> commands = new CommandLineGenerator(allTestCases, testCases, TestDataCreator.DummyExecutable.Length, "", "", TestEnvironment)
                .GetCommandLines().ToList();

            commands.Count.Should().Be(3);

            int lengthOfLongestTestname = allTests.Max(s => s.Length);
            int maxLength = CommandLineGenerator.MaxCommandLength - TestDataCreator.DummyExecutable.Length;
            int minLength = CommandLineGenerator.MaxCommandLength - lengthOfLongestTestname - TestDataCreator.DummyExecutable.Length - 1;

            string commandLine = commands[0].CommandLine;
            commandLine.Length.Should().BeLessThan(maxLength);
            commandLine.Length.Should().BeGreaterOrEqualTo(minLength);
            commandLine.Should().StartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=MyTestSuite1.*:MyTestSuite5.*:MyTestSuite0.MyTest:");

            commandLine = commands[1].CommandLine;
            commandLine.Length.Should().BeLessThan(maxLength);
            commandLine.Length.Should().BeGreaterOrEqualTo(minLength);
            commandLine.Should().NotStartWith(@"--gtest_output=""xml:"" --gtest_filter=MyTestSuite1.*:MyTestSuite5.*:");
            commandLine.Should().StartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=");

            commandLine = commands[2].CommandLine;
            commandLine.Length.Should().BeLessThan(maxLength);
            commandLine.Should()
                .NotStartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=MyTestSuite1.*:MyTestSuite5.*:");
            commandLine.Should().StartWith($@"--gtest_output=""xml:""{DefaultArgs} --gtest_filter=");

            HashSet<Model.TestCase> testsAsSet = new HashSet<Model.TestCase>(testCases);
            HashSet<Model.TestCase> splittedTestsAsSet = new HashSet<Model.TestCase>(commands[0].TestCases.Union(commands[1].TestCases).Union(commands[2].TestCases));

            splittedTestsAsSet.Should().BeEquivalentTo(testsAsSet);
        }
Example #22
0
        public int CriticalPath(int currNode, int algorithm)
        {
            int n = TopList.Count;
            NodeIsAcyclic(currNode, algorithm, false);
            if (all_neighbors_nodes.Count == 1)
            {
                if (algorithm == 2)
                    return 0;
                else if (algorithm == 3)
                    return TopList[currNode].weight;
            }

            int[,] matrix = MatrixOnlyNeighbors(all_neighbors_nodes, algorithm);

            List<int> tk = new List<int>();
            int max;

            for (int i = 0; i < n; i++)
                tk.Add(0);

            List<int> ii = new List<int>();
            List<int> jj = new List<int>();
            List<int> dij = new List<int>();

            for (int j = 0; j < n; j++)
                for (int i = 0; i < n; i++)
                    if (matrix[i, j] != 0)
                    {
                        ii.Add(i);
                        jj.Add(j);
                        dij.Add(matrix[i, j]);
                    }

            for (int i = 0; i < n; i++)
                for (int k = 0; k < ii.Count; k++)
                {
                    max = tk[ii[k]] + dij[k];
                    if (tk[jj[k]] < max)
                        tk[jj[k]] = max;
                }

            return tk.Max();                
        }
Example #23
0
        public void TestTupleVertexIndexes()
        {
            VoronoiWrapper vw = new VoronoiWrapper();
            vw.AddSegment(0, 0, 0, 10);
            vw.AddSegment(0, 10, 10, 10);
            vw.AddSegment(10, 10, 10, 0);
            vw.AddSegment(10, 0, 0, 0);
            vw.AddSegment(0, 0, 5, 5);
            vw.AddSegment(5, 5, 10, 10);
            vw.ConstructVoronoi();

            List<Tuple<double, double>> vertices = vw.GetVertices();
            List<Tuple<int, int, int, int, Tuple<bool, bool, bool, int, int>>> edges = vw.GetEdges();

            List<int> vertexIndexes = new List<int>();

            foreach (var e in edges)
            {
                if(!vertexIndexes.Exists(v=> v==e.Item2))
                    vertexIndexes.Add(e.Item2);

                if (!vertexIndexes.Exists(v => v == e.Item3))
                    vertexIndexes.Add(e.Item3);
            }

            vertexIndexes.Remove(-1);
            vertexIndexes.Sort();
            int minIndex = vertexIndexes.Min();
            int maxIndex = vertexIndexes.Max();

            Assert.AreEqual(0, minIndex);
            Assert.AreEqual(vertices.Count - 1, maxIndex);
        }
        private void AssertGeneralStuff(List<Player> players, int howManyPlayers)
        {
            // Assert the expected number of players.
             Assert.IsNotNull(players);
             Assert.AreEqual(14, players.Count);

             // Assert the TeamOrder is unique for each player.
             var uniqueTeamOrder = players.Select(p => p.TeamOrder).Distinct().ToList();
             Assert.AreEqual(howManyPlayers, uniqueTeamOrder.Count);

             // Assert the player list is ordered on the TeamOrder property.
             int minimumTeamOrder = players.Min(p => p.TeamOrder);
             var firstPlayer = players[0];
             Assert.AreEqual(minimumTeamOrder, firstPlayer.TeamOrder);
             int maximumTeamOrder = players.Max(p => p.TeamOrder);
             var lastPlayer = players[howManyPlayers - 1];
             Assert.AreEqual(maximumTeamOrder, lastPlayer.TeamOrder);

             // Assert the player list is also ordered on the rating.
             decimal maxRating = players.Max(p => p.Rating);
             var bestPlayer = players[0];
             Assert.AreEqual(maxRating, bestPlayer.Rating);
             decimal minRating = players.Min(p => p.Rating);
             var worstPlayer = players[howManyPlayers - 1];
             Assert.AreEqual(minRating, worstPlayer.Rating);
        }
Example #25
0
        public void TestTupleEdgeIndexes()
        {
            VoronoiWrapper vw = new VoronoiWrapper();
            vw.AddSegment(0, 0, 0, 10);
            vw.AddSegment(0, 10, 10, 10);
            vw.AddSegment(10, 10, 10, 0);
            vw.AddSegment(10, 0, 0, 0);
            vw.AddSegment(0, 0, 5, 5);
            vw.AddSegment(5, 5, 10, 10);
            vw.ConstructVoronoi();

            List<Tuple<int, int, int, int, Tuple<bool, bool, bool, int, int>>> edges = vw.GetEdges();

            List<int> edgeIndexes = new List<int>();

            foreach (var e in edges)
            {
                edgeIndexes.Add(e.Item1);
            }

            edgeIndexes.Sort();
            int minIndex = edgeIndexes.Min();
            int maxIndex = edgeIndexes.Max();

            Assert.AreEqual(0, minIndex);
            Assert.AreEqual(edges.Count - 1, maxIndex);
        }
        public async Task PerfomanceParallelCreateTest()
        {
            System.Diagnostics.Debug.Print("Start " + DateTime.Now.ToShortTimeString());

            Stopwatch stopwatch = new Stopwatch();
            var watch = new List<TimeSpan>();

            Parallel.For(0, 1000, (i) =>
            {
                stopwatch.Start();

                PostTest();

                stopwatch.Stop();
                watch.Add(stopwatch.Elapsed);
                stopwatch.Reset();
            });


            var count = watch.Count();
            var avg = watch.Average(r => r.Milliseconds);
            var min = watch.Min(r => r.Milliseconds);
            var max = watch.Max(r => r.Milliseconds);

            System.Diagnostics.Debug.Print("avg: {0}, min: {1}, max: {2}, count: {3}", avg, min, max, count);
            System.Diagnostics.Debug.Print("End " + DateTime.Now.ToShortTimeString());
        }
Example #27
0
        public void UtilityRandomize()
        {
            List<long> values = new List<long>();

            for (int i = 0; i < 25; i++)
            {
                long value = Extensions.Randomize(5000);
                values.Add(value);
                this.TestContext.WriteLine("{0}", value);
            }

            Assert.AreNotEqual(values.Count, values.Where(v => v == 5000).Count());
            Assert.IsTrue(values.Min() >= 4500);
            Assert.IsTrue(values.Max() <= 5500);
        }