示例#1
0
        private IEnumerable <T> PickDistinctElementsWithEqualPriorities()
        {
            var shuffle          = new FisherYatesShuffle <T>(_rng);
            var shuffledElements = shuffle.Shuffle(_pairs.Select(p => p.Value), _numberOfElements);

            return(shuffledElements.Take(_numberOfElements).ToList());
        }
        public void PermutationsShouldBeUnbiased(int count)
        {
            // Arrange
            var data         = Enumerable.Range(1, count).ToArray();
            var permutations = PermutationLexicographicOrdering.EnumeratePermutations(data)
                               .ToDictionary(Stringify, x => 0);

            var random  = new RandomWithSeed();
            var shuffle = new FisherYatesShuffle(random);

            var idealNumberOfOccurrences = 10000;
            var trials = permutations.Count * idealNumberOfOccurrences;

            // Act
            for (var i = 0; i < trials; ++i)
            {
                var tmp = Enumerable.Range(1, count).ToArray();
                shuffle.Shuffle(tmp);
                permutations[Stringify(tmp)]++;
            }

            // Assert
            var deviation  = 0.04;
            var maxAllowed = (int)(idealNumberOfOccurrences * (1 + deviation));
            var minAllowed = (int)(idealNumberOfOccurrences * (1 - deviation));

            foreach (var pair in permutations)
            {
                var occurences = pair.Value;
                var message    = $"Expected permutation to be yielded {minAllowed} <= x <= {maxAllowed} times, " +
                                 $"but was {occurences}. Seed: {random.Seed}";

                Assert.True(occurences >= minAllowed && occurences <= maxAllowed, message);
            }
        }
        public void Shuffling_empty_list_should_do_nothing()
        {
            var empty = Array.Empty <int>();

            FisherYatesShuffle.Shuffle(empty);
            empty.Should().BeEmpty();
        }
        public void NullShuffle_Int_DoesShuffle(
            IEnumerable <int> input, FisherYatesShuffle sut)
        {
            var result = sut.Shuffle(input);

            VerifyShuffle(input, result);
        }
        public void NullShuffle_Location_DoesShuffle(
            IEnumerable <Location> input, FisherYatesShuffle sut)
        {
            var result = sut.Shuffle(input);

            VerifyShuffle(input, result);
        }
示例#6
0
        /// <summary>
        /// Expands and shuffles the existing dataset with various affine transformations.
        /// </summary>
        /// <returns></returns>
        public List <MnistImage> ExpandDataset()
        {
            var result = new List <MnistImage>();

            Console.WriteLine("Reading images from disk");

            List <MnistImage> dataset = GetDataset();

            Console.WriteLine("Applying translation transformation");

            List <MnistImage> translatedImages = ApplyTranslationTransformation(dataset);

            Console.WriteLine("Applying rotation transformation");

            List <MnistImage> rotatedImages = ApplyRotationTransformation(dataset);

            result.AddRange(dataset);

            result.AddRange(translatedImages);

            result.AddRange(rotatedImages);

            Console.WriteLine("Shuffling images");

            return(FisherYatesShuffle.Shuffle(result));
        }
示例#7
0
        public void Shuffle_WithNParameter_AllNValuesCanChangePosition()
        {
            var rng     = new DefaultRandomNumberGenerator();
            var shuffle = new FisherYatesShuffle <ValuePriorityPair <int> >(rng);

            Assert.That.AllNValuesCanChangePositions(shuffle);
        }
示例#8
0
    private void InitializeAI(BetAmount betAmount)
    {
        AIUnit ai = ai_units.Find(p => (p.m_BetAmount == betAmount));

        mInfo = new List <QuestionAnswerInfo>();

        int correctNum = Random.Range(ai.m_QuestionToAnswer.MinQuestionsToBeAnswered, ai.m_QuestionToAnswer.MaxQuestionsToBeAnswered + 1);

        int TimeToAnswer = 0;

        for (int i = 0; i < MULTIPLAYER_QUESTION_NUMBER; i++)
        {
            QuestionAnswerInfo tInfo = new QuestionAnswerInfo();

            int answerInWithin = Random.Range(ai.MinTimeToAnswer, ai.MaxTimeToAnswer);

            tInfo.AnsweredInTime = answerInWithin;

            TimeToAnswer = (i == 0) ? maxAllowedTime - answerInWithin : TimeToAnswer - answerInWithin;

            tInfo.TimeToAnswerQuestion = TimeToAnswer;//UnityEngine.Random.Range(ai.MinTimeToAnswer, ai.MaxTimeToAnswer);

            mInfo.Add(tInfo);
        }

        FisherYatesShuffle obj = new FisherYatesShuffle(5);

        obj.ShuffleList();
        List <int> correctIndex = obj.ShuffledList;

        for (int i = 0; i < correctNum; i++)
        {
            mInfo[correctIndex[i]].isCorrectAnswer = true;
        }
    }
示例#9
0
        public void TestShuffle()
        {
            FisherYatesShuffle fisherYatesShuffle = new FisherYatesShuffle(N, StartFrom);

            PrintIntegerList(fisherYatesShuffle.ShuffledList);
            fisherYatesShuffle.ShuffleList();
            PrintIntegerList(fisherYatesShuffle.ShuffledList);
        }
        public void Shuffling_null_should_throw_ArgumentNullException()
        {
            IList <int> list = null;

            var exception = Record.Exception(() => FisherYatesShuffle.Shuffle(list));

            exception.Should().BeOfType <ArgumentNullException>();
        }
        public void Shuffling_single_element_list_should_do_nothing()
        {
            var list = new List <int> {
                42
            };

            FisherYatesShuffle.Shuffle(list);
            list.Should().ContainSingle(x => x == 42);
        }
示例#12
0
        public void ShuffleEnumerable_ShufflesElements()
        {
            var rnd = new Random(1);
            IEnumerable <int> arr      = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            IEnumerable <int> expected = new[] { 9, 3, 7, 5, 4, 1, 10, 8, 2, 6 };

            arr = FisherYatesShuffle.Shuffle(arr.AsEnumerable(), rnd);

            Assert.Equal(expected, arr);
        }
示例#13
0
        public void ShuffleInPlace_ShufflesElements()
        {
            var rnd = new Random(1);

            int[] arr      = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int[] expected = { 7, 9, 5, 2, 10, 8, 6, 4, 1, 3 };
            FisherYatesShuffle.ShuffleInPlace(arr, rnd);

            Assert.Equal(expected, arr);
        }
示例#14
0
        private static void ShuffleAndQueueTracks(BufferItem item, BufferList playQueue, BufferList tracklist)
        {
            var algorithm = new FisherYatesShuffle(new RandomWrapper());
            var shuffled  = tracklist.Shuffle(algorithm).ToList();

            foreach (var shuffledItem in shuffled.Where(i => i != item))
            {
                playQueue.Add(shuffledItem);
            }
        }
示例#15
0
        public void Shuffle_ShufflesElements()
        {
            var rnd = new Random(1);

            int[] arr      = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int[] expected = { 9, 3, 7, 5, 4, 1, 10, 8, 2, 6 };
            arr = FisherYatesShuffle.Shuffle(arr, rnd);

            Assert.Equal(expected, arr);
        }
        public SectionTwo()
        {
            // Blum Blum Shub RNG
            blumBlumShub = new BlumBlumShub();

            // Randomizing by shuffling, Algorithm B, by defualt using original RNG
            randomShuffle = new AlgorithmBShuffling(blumBlumShub);

            // Fisher-Yates Shuffle with Blum Blum Shub RNG
            fisherYatesShuffle = new FisherYatesShuffle(randomShuffle);
        }
示例#17
0
    private void ExcuteShuffle()
    {
        float startTime = Time.realtimeSinceStartup;

        FisherYatesShuffle.Shuffle <GameObject>(ShuffleArray);
        double elapsedTime = Time.realtimeSinceStartup - startTime;

        Debug.LogFormat("Shuffle done! : {0}sec", elapsedTime);

        isStart = true;
    }
示例#18
0
        public void FisherYate_Shuffle( int num )
        {
            var source = CreateSample( num );
            var sample = new List<int>( source );
            var shuffled = FisherYatesShuffle.Shuffle( source );

            ValidateWithSource( sample, shuffled );

            var shuffled2 = FisherYatesShuffle.Shuffle( source );
            ValidateWithOther( shuffled, shuffled2 );
        }
示例#19
0
    public BaseQuestion GetUIQuestion(int questionIndex, int answerButtons = 4)
    {
        ConfusionTouch questionType = ConfusionTouchList[questionIndex];

        AnswerInfos.Clear();

        CurrentColorID = AnswerID.None;

        int colors = EnumUtil.GetValues <ColorEnum>().Count;

        //Initializing a Question
        BaseQuestion bq = new BaseQuestion();

        bq.IgnoreClickCount       = true;
        bq.IgnoreClickTime        = true;
        bq.HasSequenceAnswer      = false;
        bq.HasBoolValue           = false;
        bq.HasTimerValue          = true;
        bq.HasSequentialQuestions = true;
        bq.Pattern         = QPattern.ConfusionTouch;
        bq.QuestionType    = QuestionType.Base;
        bq.TimeForQuestion = 0;
        bq.Options         = new List <AnswerSpriteHolder>();
        for (int i = 0; i < answerButtons; i++)
        {
            AnswerSpriteHolder answer = new AnswerSpriteHolder();
            bq.Options.Add(answer);
        }
        //

        //Getting a random color for the question
        int randomColorIndex = (int)Random.Range(0, colors);

        //Shuffle
        FisherYatesShuffle shuffle = new FisherYatesShuffle(colors);

        shuffle.ShuffleList();
        List <int> colorIndex = shuffle.ShuffledList;

        //Setting up button info for later assignment and setting up current answerID Color for the current question
        for (int i = 0; i < answerButtons; i++)
        {
            ConfusionTouchAnswerInfo answerInfo = GetNewAnswerButton();
            AnswerInfos.Add(answerInfo);
        }

        SetAnswerForQuestion();
        SetAnswerID((ColorEnum)randomColorIndex);

        //Assignment to answer buttons
        SetAnswerOption(ref bq, (ColorEnum)randomColorIndex, questionType);

        return(bq);
    }
示例#20
0
        public void Test()
        {
            int max = 100;
            int k   = 7;

            int[] nums = Enumerable.Range(0, max + 1).ToArray();

            FisherYatesShuffle.ShuffleInPlace(nums);

            int hi = KthHighestNumber.Calc(nums, k);

            Assert.Equal(max - k + 1, hi);
        }
        public void TestRandomSelectionOfFisherYatesAlgorithm([Range(0, 10)] int seed)
        {
            //Arrange
            const int expectedSelectionCount = 3;
            var       originalItems          = new[] { 1, 2, 3, 4, 5 };

            //Act
            var selection = FisherYatesShuffle.RandomSelection(originalItems, expectedSelectionCount, seed);

            //Assert
            Assert.AreEqual(expectedSelectionCount, selection.Length, $"Failed with seed: {seed}");
            Assert.AreEqual(selection.Length, selection.Distinct().Count(), $"Failed with seed: {seed}");
            CollectionAssert.IsSubsetOf(selection, originalItems, $"Failed with seed: {seed}");
        }
示例#22
0
    private void Shuffle <T>(ref List <T> ilist)
    {
        FisherYatesShuffle shuffle = new FisherYatesShuffle(ilist.Count, 0);

        shuffle.ShuffleList();
        List <int> shuffleList  = shuffle.ShuffledList;
        List <T>   shuffledList = new List <T>();

        for (int i = 0; i < shuffleList.Count; i++)
        {
            shuffledList.Add(ilist[shuffleList[i]]);
        }
        ilist = shuffledList;
    }
示例#23
0
    private void Shuffle <T>(ref T[] iArray)
    {
        FisherYatesShuffle shuffle = new FisherYatesShuffle(iArray.Length, 0);

        shuffle.ShuffleList();
        List <int> shuffleList  = shuffle.ShuffledList;
        List <T>   shuffledList = new List <T>();

        for (int i = 0; i < shuffleList.Count; i++)
        {
            shuffledList.Add(iArray[shuffleList[i]]);
        }
        iArray = shuffledList.ToArray();
    }
        public void Shuffling_a_large_list_should_shuffle_order()
        {
            var list = Enumerable.Range(0, 100).ToList();
            var elementsInOriginalOrder = new List <int>(list);

            FisherYatesShuffle.Shuffle(list);
            // Verify that all the elements are present in some order.
            list.Should().Contain(elementsInOriginalOrder);
            // Verify that the elements are not in the original order.
            // NOTE: There is a 1 in N! chance that the shuffled element order
            //       will match the original element order. This is statistically
            //       extremely unlikely when N = 100.
            list.Should().NotEqual(elementsInOriginalOrder);
        }
示例#25
0
        public Question(IEnumerable<Phrase> allPhrases, Difficulty questionDifficulty)
        {
            IShuffler<Phrase> phraseShuffler = new FisherYatesShuffle<Phrase>();

            IEnumerable<Phrase> phrasesThatMatchDifficulty = allPhrases.Where(phrase => questionDifficulty.HasFlag(phrase.Difficulty));

            IEnumerable<Phrase> shuffledPhrases = phraseShuffler.Shuffle(phrasesThatMatchDifficulty, 4);

            displayedPhrases = shuffledPhrases.ToList();

            Random randomPhraseGenerator = new Random();

            int randomPhraseIndex = randomPhraseGenerator.Next(0, displayedPhrases.Count());

            correctPhrase = displayedPhrases[randomPhraseIndex];
        }
示例#26
0
        public void FisherYate_Draw( int num )
        {
            var sample = new List<int>( CreateSample( num ) );
            var shuffled = new List<int>( FisherYatesShuffle.Draw( sample ) );

            var sourceValidationError = "Source data has currupted";
            Assert.AreEqual( num, sample.Count, sourceValidationError );
            for ( int i=0; i < sample.Count; ++i ) {
                Assert.AreEqual( i, sample[i], sourceValidationError );
            }

            ValidateWithSource( sample, shuffled );

            var shuffled2 = new List<int>( FisherYatesShuffle.Draw( sample ) );
            ValidateWithOther( shuffled, shuffled2 );
        }
        void IDnsMonitoringCluster.ProcessDnsResults(List <DnsEndPoint> dnsEndPoints)
        {
            if (dnsEndPoints.Count == 0)
            {
                return;
            }

            // Assuming that before this method one from the following conditions has been validated:
            // 1. The cluster type is Unknown or Sharded.
            // 2. This method has been called the first time.
            // Otherwise, the below code should not be called.
            var newServers = new List <IClusterableServer>();

            lock (_updateClusterDescriptionLock)
            {
                var oldClusterDescription = Description;

                var newClusterDescription = oldClusterDescription;
                var currentEndPoints      = oldClusterDescription.Servers.Select(serverDescription => serverDescription.EndPoint).ToList();

                var endPointsToRemove = currentEndPoints.Where(endPoint => !dnsEndPoints.Contains(endPoint));
                foreach (var endPoint in endPointsToRemove)
                {
                    newClusterDescription = RemoveServer(newClusterDescription, endPoint, "Server no longer appears in the DNS SRV records.");
                }

                var endPointsToAdd = dnsEndPoints.Where(endPoint => !currentEndPoints.Contains(endPoint)).ToList();
                var srvMaxHosts    = Settings.SrvMaxHosts;
                if (srvMaxHosts > 0)
                {
                    FisherYatesShuffle.Shuffle(endPointsToAdd);
                    endPointsToAdd = endPointsToAdd.Take(srvMaxHosts - currentEndPoints.Count + endPointsToRemove.Count()).ToList();
                }
                foreach (var endPoint in endPointsToAdd)
                {
                    newClusterDescription = EnsureServer(newClusterDescription, endPoint, newServers);
                }

                newClusterDescription = newClusterDescription.WithDnsMonitorException(null);
                UpdateClusterDescription(newClusterDescription);
            }

            foreach (var addedServer in newServers)
            {
                addedServer.Initialize();
            }
        }
示例#28
0
        public Deck()
        {
            cards    = new Card[CardsInDeck];
            Shuffler = new FisherYatesShuffle();

            var suits = new[]
            {
                CardSuit.Diamonds,
                CardSuit.Clubs,
                CardSuit.Hearts,
                CardSuit.Spades
            };

            for (int i = 0; i < SuitsInDeck; i++)
            {
                CardSuit suit = suits[i];


                for (int j = 0; j < CardsPerSuit; j++)
                {
                    var index = j + (i * CardsPerSuit);

                    var value = j + 1;
                    int gameValue;

                    switch (value)
                    {
                    case 1:
                        // aces are high
                        gameValue = 14;
                        break;

                    case 2:
                        // 2's are the highest valued cards in this game.
                        gameValue = 15;
                        break;

                    default:
                        gameValue = value;
                        break;
                    }

                    cards[index] = new Card(value, gameValue, suit);
                }
            }
        }
示例#29
0
        public void ShuffleTests()
        {
            FisherYatesShuffle shuffle = new FisherYatesShuffle(new RandomRandomNumberGenerator(seed: 42));

            List <int> testList = this.CreateTestList();

            shuffle.Shuffle(testList);

            CollectionAssert.AreEqual(new List <int>()
            {
                1, 9, 8, 6, 4
            }, testList);

            shuffle.Shuffle(testList);
            CollectionAssert.AreEqual(new List <int>()
            {
                8, 9, 4, 1, 6
            }, testList);
        }
示例#30
0
    private void PointSourceGenerator(Transform mapHolder, bool[,] obstacleMap)
    {
        //shuffled accessibleTileCoords
        accessibleTileCoords = new Queue <Coord> (FisherYatesShuffle.ShuffleArray(accessibleTileCoords.ToArray(), seed));
        for (int i = 0; i < pointSourceNumber; i++)
        {
            Coord randomAccessibleTile = accessibleTileCoords.Dequeue();
            if (obstacleMap[randomAccessibleTile.x, randomAccessibleTile.y])
            {
                i--;
                continue;
            }
            Vector3 pointSourcePosition = CoordToPosition(randomAccessibleTile.x, randomAccessibleTile.y);


            Transform newPoint = Instantiate(pointSourcePrefab, pointSourcePosition + new Vector3(0, .5f, 0), Quaternion.identity);
            newPoint.parent = mapHolder;
        }
    }
示例#31
0
        public void ShuffleTileStack()
        {
            if (_allTilesWithoutSpecial.Count == 0)
            {
                Debug.LogError($"Tile stack is empty! Run {nameof(GenerateTileStack)} first");
            }
            var tilesToShuffle = _allTilesWithoutSpecial.ToArray();

            for (int i = 0; i < TIMES_TO_SHUFFLE; i++)
            {
                FisherYatesShuffle.ShuffleSequence(tilesToShuffle);
            }
            _allTilesWithoutSpecial = new List <TileData>(tilesToShuffle);
            if (!string.IsNullOrEmpty(_specialTileName) && _specialTilePosition > 0)
            {
                AddSpecialTileAtPosition(_specialTileName, _specialTilePosition);
            }
            AddTilesToStack();
        }