Beispiel #1
0
        public void TestCalculateProbabilityAtLeastOnePersonGetsTheirOwnHat(int numHats, double expectedProbabilitySomeoneDrawsOwnHat)
        {
            double epsilon          = 0.0001;
            var    hatProblemSolver = new HatProblemSolver();
            var    actualProbabilitySomeoneDrawsOwnHat = hatProblemSolver.CalculateProbabilityAtLeastOnePersonGetsTheirOwnHat(numHats);

            var permutationGenerator = new PermutationGenerator();
            var permutations         = permutationGenerator.GeneratePermutationsOfNObjects(numHats);
            var actualProbabilitySolvedThroughPermutations =
                (double)permutations.Where(p => p.ContainsAtLeastOneFixedPoint()).Count() / (double)permutations.Count();

            Assert.LessOrEqual(Math.Abs(expectedProbabilitySomeoneDrawsOwnHat - actualProbabilitySomeoneDrawsOwnHat), epsilon);
            Assert.LessOrEqual(Math.Abs(expectedProbabilitySomeoneDrawsOwnHat - actualProbabilitySolvedThroughPermutations), epsilon);
        }
Beispiel #2
0
        public void TestGeneratePermutations(int n)
        {
            var permutationGenerator = new PermutationGenerator();
            var permutations         = permutationGenerator.GeneratePermutationsOfNObjects(n);
            int nFactorial           = Enumerable.Range(1, n).Aggregate(1, (p, item) => p * item);

            Assert.AreEqual(nFactorial, permutations.Count);
            var maxScore = 0;

            // note, this only works for n < 10
            foreach (var permutation in permutations)
            {
                var score = int.Parse(permutation.GetPermutation().Aggregate("", (score, i) => $"{score}{i}"));
                Assert.Greater(score, maxScore);
                maxScore = score;
            }
        }