Example #1
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 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 #4
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 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);
        }
        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");
        }
        public void MinTest()
        {
            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(1, posIntList.Min());
            Assert.AreEqual(-9, intList.Min());
            Assert.AreEqual(.1m, posDecimalList.Min());
            Assert.AreEqual(-.9m, decimalList.Min());
        }
        public void Min_abnormal()
        {
            // arrange
            List<int> listInt = new List<int>();
            Func<int, int> func = null;

            // act and assert
            try
            {
                listInt.Min(func);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is ArgumentNullException);
            }
            try
            {
                listInt.Min(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_Min_ReturnsMinValue()
        {
            var list = new List<Int32>() { 4, 5, 6, 99, 10, 1, 12, 45 };

            var result = list.Min();

            TheResultingValue(result).ShouldBe(1);
        }
        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 #12
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);
        }
Example #13
0
        public void Min()
        {
            // 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.Min(x => x);
            double actuallong = listlong.Min(x => x);
            double actualdouble = listdouble.Min(x => x);
            decimal actualdecimal = listdecimal.Min(x => x);

            // assert
            Assert.AreEqual(1, actualInt, 0);
            Assert.AreEqual(1, actuallong, 0);
            Assert.AreEqual(1d, actualdouble, 0);
            Assert.AreEqual(1, actualdecimal);
        }
        public void ListExtensions_Min_ThrowsExceptionIfListIsEmpty()
        {
            var list = new List<Int32>();

            list.Min();
        }
Example #15
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");
        }
Example #16
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 #18
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 #19
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);
        }