public BackPackIndividual BruteForce(BackPackEnvironment environment)
        {
            var possibleIndividuals = new List<BackPackIndividual>();

            int genomeSize = environment.ComputeGenomeSize();

            var chromosome = new int[genomeSize];
            var posssibilitiesPerInt = environment.AvailableItems.Count > 31 ?
                uint.MaxValue :
                (uint)1 << environment.AvailableItems.Count; // 2^n
            
            for (uint i = 0; i < posssibilitiesPerInt; i++)
            {
                for (int j = 0; j < genomeSize; j++)
                {
                    chromosome[j] = (int)i;
                    var individual = new BackPackIndividual(environment);
                    individual.Genome.Chromosome = (int[])chromosome.Clone();

                    if (environment.Validate(individual))
                    {
                        possibleIndividuals.Add(individual);
                    }
                }
            }

            return possibleIndividuals.Aggregate((a, b) => environment.RateFitness(a) > environment.RateFitness(b) ? a : b);
        }
Esempio n. 2
0
        public void WhenADeckIsFlipped_TheCardsAreInExactlyTheReverseOrder()
        {
            var deck = new Deck();
            var expectedCardString = string.Empty;

            // Add Cards to Deck
            for (var i = 1; i <= 9; i++)
            {
                var card = deck.Push(new Cards.Number(i, CardColour.Blue));
                expectedCardString += string.Format("{0}{1}{2}", card.GetType(), card.Colour, card.Value);
            }

            // Flip the Deck
            deck.Flip();

            // Remove Cards from Deck
            var cards = new List<ICard>();
            while (deck.NumberOfCardsInDeck > 0)
            {
                cards.Add(deck.Pop());
            }

            // Build Compare Strings in reverse order because the Deck is a Stack (LIFO).  (I understand due to the way shuffling occurs that in theory the decks could be identical in some universe)
            var actualCardString = cards.Aggregate(string.Empty,
                                                   (current, t) =>
                                                   current + string.Format("{0}{1}{2}", t.GetType(), t.Colour, t.Value));

            Assert.AreEqual(actualCardString, expectedCardString);
        }
        public void GetBatchMessage()
        {
            var messages = new List<string> { "1", "2" };
            string batchMessages = messages.Aggregate("", (current, message) => current + (message + ","));

            Request request = new Request(ExtensionMessageEndPoint + "/" + batchMessages);
            Response response = RingCentralClient.GetPlatform().Get(request);
            Assert.IsTrue(response.IsMultiPartResponse());
            List<string> multiPartResult = response.GetMultiPartResponses();

            //We're interested in the response statuses and making sure the result was ok for each of the message id's sent.
            JToken responseStatuses = JObject.Parse(multiPartResult[0]);
            for (int i = 0; i < messages.Count; i++)
            {
                var status = (string)responseStatuses.SelectToken("response")[i].SelectToken("status");
                Assert.AreEqual(status, "200");
            }

            foreach (string res in multiPartResult.Skip(1))
            {
                JToken token = JObject.Parse(res);
                var id = (string)token.SelectToken("id");
                Assert.IsNotNull(id);
            }

        }
 public void TestSumAggregate()
 {
     List<int?> l = new List<int?>
     {
         0,
         3,
         null,
         4,
         5
     };
     int? sum = l.Sum();
     int? agg = l.Aggregate((int?)0, (s, x) => s + x);
     Assert.IsFalse(sum == null);
     Assert.IsTrue(agg == null);
 }
Esempio n. 5
0
        public void Should_return_an_empty_list()
        {
            var SearchTags = new List<string> { "test" };
            using (var mongo = new Mongo())
            {
                mongo.Connect();
                var db = mongo.GetDatabase("posts");
                var posts = db.GetCollection<Post>();
                posts.Remove(x => true);
                posts.Insert(new Post() { Tags = new List<string> { "test", "funny" } });

                var result = SearchTags
                    .Aggregate(posts.Linq(), (current, tag) => current.Where(x => x.Tags.Contains(tag)))
                    .OrderByDescending(x => x.LastAccess)
                    .ToList();

                Assert.AreEqual(1, result.Count);
            }
        }
Esempio n. 6
0
        private static int CalculatePrice(List<string> cart)
        {
            cart.Sort();

            List<List<string>> resultSet = new List<List<string>>();

            // TODO NEXT TIME
            // create permutations --> and calcPrice on those
            // find cheapest
            //  OR
            // calc price for each potential set?

            while (cart.Count > 0)
            {
                List<string> currentSet = GetSetThatDoesntHaveTheBook(cart[0], resultSet);

                if (currentSet == null)
                {
                    currentSet = new List<string>();
                    resultSet.Add(currentSet);

                }
                else
                {
                    currentSet.Add(cart[0]);
                    cart.RemoveAt(0);
                }

            }

            //Assert.That(resultSet.Count, Is.EqualTo(2));

            int calculatePrice =
                resultSet.Aggregate(
                0,
                (total, set) => total + CalculateSetPrice(set));

            //Assert.That(resultSet[0].Count, Is.EqualTo(2));
            //Assert.That(resultSet[1].Count, Is.EqualTo(1));

            //Assert.That(price1, Is.EqualTo(1520));
            //Assert.That(price2, Is.EqualTo(800));

            return calculatePrice;
        }
Esempio n. 7
0
        public void TwoSameBooks_Costs1600C()
        {
            List<string> cart = new List<string>();

            cart.Add("Harry1");
            cart.Add("Harry1");

            double price = 0;

            price =
            cart.Aggregate(
                0,
                (total, title) => total + 800);

            Assert.That(price, Is.EqualTo(1600));
        }
 private static Expr BuildExpr(Expr[] vars, bool[] truthTable) {
     var vLen = vars.Length;
     var e = truthTable
         .Select((x, i) => new { x, i })
         .Where(x => x.x)
         .Select(x => x.i)
         .Aggregate((Expr)ctx.Literal(false), (acc, b) => {
             var ands = new List<Expr>();
             for (int i = 0, mask = 1; i < vLen; i++, mask <<= 1) {
                 if ((b & mask) != 0) {
                     // true
                     ands.Add(vars[i]);
                 } else {
                     // false
                     ands.Add(ctx.ExprGen.Not(vars[i]));
                 }
             }
             return ctx.ExprGen.Or(acc, ands.Aggregate((x, y) => ctx.ExprGen.And(x, y)));
         });
     return e;
 }
Esempio n. 9
0
		public void PropertyChanges()
		{
			var task = new Task("A", new List<string> {"+fixsink", "+writenovel"},
			                    new List<string> {"@home", "@work"},
			                    "Write a chapter about fixing the sink");

			task.DueDate = DateTime.Now.AddDays(3).ToString();

			bool fired = false;

			List<String> changedProperties = new List<string>();

			task.PropertyChanged += (sender, e) =>
				{
					fired = true;
					changedProperties.Add(e.PropertyName);
				};

			// Setting task values to their current value shouldn't fire PropertyChanged
			task.Priority = task.Priority;
			task.DueDate = task.DueDate;
			task.Body = task.Body;

			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));

			Assert.False(fired);

			// Setting them to new values should fire PropertyChanged
			task.Priority = "B";
			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));
			Assert.True(fired);
			fired = false;

			task.DueDate = DateTime.Now.AddDays(4).ToString();
			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));
			Assert.True(fired);
			fired = false;

			task.Body = "Delete chapter about the sink";
			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));
			Assert.True(fired);
		}
Esempio n. 10
0
        public void FluentSearchOfDifferentFieldsInAListSerializesCorrectly()
        {
            var fieldsAndValues = new List<Tuple<string, string>>
            {
                Tuple.Create("field1", "value1"),
                Tuple.Create("field2", "value2"),
                Tuple.Create("field3", "value3"),
                Tuple.Create("field4", "value4"),
                Tuple.Create("field5", "value5"),
            };

            var s = fieldsAndValues.Aggregate((Term)null,
                (a, t) => a == null ? new RiakFluentSearch("bucket", t.Item1).Search(t.Item2) : a.And(t.Item1, t.Item2))
                .Build();

            var q = s.ToString();
            Assert.AreEqual("field1:value1 AND field2:value2 AND field3:value3 AND field4:value4 AND field5:value5", q);
        }
Esempio n. 11
0
        public void FluentSearchOfSameFieldsInAListSerializesCorrectly()
        {
            var fieldsAndValues = new List<string>
            {
                "value1",
                "value2",
                "value3",
                "value4",
                "value5"
            };

            var s = fieldsAndValues.Aggregate((Term)null,
                (a, v) => a == null ? new RiakFluentSearch("bucket", "field").Search(v) : a.And(v))
                .Build();

            var q = s.ToString();
            Assert.AreEqual("field:value1 AND field:value2 AND field:value3 AND field:value4 AND field:value5", q);
        }
            public void SaveVehicle()
            {
                var results = new List<string>();
                var success = true;
                using (var session = NHibernateSession.Current)
                using (var trans = session.BeginTransaction())
                {
                    var vehicle = GetValidVehicle();
                    session.Save(vehicle);
                    if (vehicle.Id == 0)
                    {
                        results.Add("Failed to save vehicle");
                        success = false;
                    }
                    if (success)
                    {
                        results.Add("Success");
                    }
                    trans.Rollback();
                }

                Assert.IsTrue(success, results.Aggregate((i, j) => i + j));
            }
Esempio n. 13
0
        protected void Run(Action whatToRun, string testNameSuffix = "", Action before = null, Action after = null)
        {
            before = before ?? new Action(() => {});
            after = after ?? new Action(() => {});
            var success = false;
            var tries = 1;
            var fails = new List<string>();

            while(!success)
            {
                results = new List<double>();
                for(var i = 0; i < WarmUpRounds; i++)
                {
                    before();
                    whatToRun();
                    after();
                }

                while(true)
                {
                    before();
                    Measure(whatToRun);
                    after();

                    if(results.Count >= MinimalNumberOfRuns)
                    {
                        var currentAverage = results.Average();
                        var currentStdDev = results.StandardDeviation();
                        results.RemoveAll(x => Math.Abs(x - currentAverage) > 3*currentStdDev);
                        currentStdDev = results.StandardDeviation();
                        currentAverage = results.Average();
                        if(currentStdDev/currentAverage <= MinimalRequiredStandardDeviation)
                        {
                            success = true;
                            break;
                        }
                    }
                    if(results.Count > MaximalNumberOfRuns)
                    {
                        fails.Add(string.Format("Maximal number of runs {0} was exceeded, with standard deviation {1:0.00} > {2:0.00}. (Try {3}).", MaximalNumberOfRuns,
                                               results.StandardDeviation()/results.Average(), MinimalRequiredStandardDeviation, tries));
                        break;
                    }
                }
                if(tries++ >= MaximalRetriesCount)
                {
                    Assert.Fail(fails.Aggregate((x, y) => x + Environment.NewLine + y));
                }
            }
            var average = results.Average();
            var stdDev = results.StandardDeviation();
            var testName = string.Format("{0}:{1}", TestContext.CurrentContext.Test.Name, testNameSuffix);
            resultsDb.Append(new Result(testName, average, stdDev, SetUp.TestDate));
            File.AppendAllLines(SetUp.TestLogFileName, new [] { string.Format("{0}\t{1}s\t{2:0.00}", testName, average.NormalizeDecimal(), stdDev/average) } );
        }