Example #1
0
        private double CalculateCoverage()
        {
            var range       = MaximumToolCoverage - MininumToolCoverage;
            var rawCoverage = _random.Generate(MininumToolCoverage, range);

            return(rawCoverage.Clip(0, 100));
        }
        /// <summary>
        ///   Creates a square matrix matrix with random data.
        /// </summary>
        ///
        public static T[][] Random <T>(int size, IRandomNumberGenerator <T> generator,
                                       bool symmetric = false, T[][] result = null)
        {
            if (result == null)
            {
                result = Jagged.Create <T>(size, size);
            }

            if (!symmetric)
            {
                for (int i = 0; i < size; i++)
                {
                    result[i] = generator.Generate(size);
                }
            }
            else
            {
                for (int i = 0; i < size; i++)
                {
                    T[] row = generator.Generate(size / 2, result[i]);
                    for (int start = 0, end = size - 1; start < size / 2; start++, end--)
                    {
                        row[end] = row[start];
                    }
                }
            }

            return(result);
        }
Example #3
0
        ///<inheritdoc/>
        public ChunkInfo Build(long chunkSize)
        {
            var entryInfos = new List <EntryInfo>();
            var diff       = _encodingInfoProvider.GetStringLength(chunkSize);

            //First entry of chunk should be repeated
            var repeatedEntryLength = _randomNumberGenerator.Generate(EntryInfo.MinLength, EntryInfo.MaxEntryLength);

            if (repeatedEntryLength * 2 >= diff - EntryInfo.MinLength)
            {
                // In this case chunk will be small and contain only row and repeated row
                return(new ChunkInfo(new List <EntryInfo>(), CreateEntryInfo((int)diff / 2)));
            }

            var repeatedEntryInfo = CreateEntryInfo(repeatedEntryLength);

            diff -= repeatedEntryLength * 2;

            while (diff > 0)
            {
                var nextLength  = _randomNumberGenerator.Generate(EntryInfo.MinLength, EntryInfo.MaxEntryLength);
                var totalLength = nextLength < diff - EntryInfo.MinLength ? nextLength : diff;
                entryInfos.Add(CreateEntryInfo((int)totalLength));
                diff -= totalLength;
            }

            return(new ChunkInfo(entryInfos, repeatedEntryInfo));
        }
Example #4
0
        public void SetWinningDoor(List <Door> allDoors)
        {
            var randomNumber = _randomNumberGenerator.Generate();
            var currentDoor  = allDoors.Find(door => door.Number == randomNumber);

            currentDoor.Winner = true;
        }
Example #5
0
        public PlanFeature BuildPlanFeature(Feature feature)
        {
            var planFeature     = new PlanFeature("Plan" + feature.Name, feature);
            var count           = _random.Generate(1, NumberOfMeasurementSets);
            var measurementSets = Enumerable.Range(0, count)
                                  .Select(i => BuildMeasurementSet(planFeature)).ToImmutableList();

            return(planFeature.With(measurementSets));
        }
 public ActionResult <IEnumerable <int> > Get()
 {
     return(new int[]
     {
         _rand.Generate(),
         _rand.Generate(),
         _rand.Generate(),
         _rand.Generate()
     });
 }
Example #7
0
        private Feature BuildFeature(int partSize, int index)
        {
            var name      = "Feature" + index;
            var center    = _random.Generate(Point3D.Origin, partSize);
            var direction = _random.Generate(Point3D.Origin, 1)
                            .ToVector3D().ToDirection3D();
            var featureSize = _random.Generate(0, partSize);

            return(new Feature(name, center, direction, featureSize));
        }
Example #8
0
 private IEnumerable <MeasurementSetNode> SortMeasurementSetNodes(IImmutableList <MeasurementSetNodeResult> measurementSetNodeResults)
 {
     foreach (var measurementSetNodeResult in measurementSetNodeResults)
     {
         var measurementSetNodes = measurementSetNodeResult.MeasurementSetNodes;
         if (measurementSetNodes.Count == 1)
         {
             yield return(measurementSetNodes.First());
         }
         var index = _random.Generate(0, measurementSetNodes.Count);
         yield return(measurementSetNodes[index]);
     }
 }
        public SymbolOptions ChooseSymbol()
        {
            // generates a value in [0,maxValue) so we add 1 to create a [1,100] percentage
            int percentage = _generator.Generate(max: 100) + 1;

            SymbolOptions chosenSymbol = null;

            // since symbols are a low count an O(N) algorithm is good enough
            // an O(logN) one may result in a more complex implementation which is harder to support with no actual benefits
            foreach (SymbolOptions currentSymbol in _options.Symbols)
            {
                if (percentage <= currentSymbol.Probability)
                {
                    chosenSymbol = currentSymbol;
                    break;
                }
                else
                {
                    percentage -= currentSymbol.Probability;
                }
            }

            if (chosenSymbol == null)
            {
                throw new InvalidOperationException("Failed to generate a symbol.");
            }

            _logger.LogDebug("Generated symbol {0}.", chosenSymbol);
            return(chosenSymbol);
        }
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        ///
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect)
        {
            int pixelSize = (image.PixelFormat == PixelFormat.Format8bppIndexed) ? 1 : 3;

            int startY = rect.Top;
            int stopY  = startY + rect.Height;

            int startX = rect.Left * pixelSize;
            int stopX  = startX + rect.Width * pixelSize;

            int offset = image.Stride - (stopX - startX);

            // do the job
            byte *ptr = (byte *)image.ImageData.ToPointer();

            // allign pointer to the first pixel to process
            ptr += (startY * image.Stride + rect.Left * pixelSize);

            // for each line
            for (int y = startY; y < stopY; y++)
            {
                // for each pixel
                for (int x = startX; x < stopX; x++, ptr++)
                {
                    *ptr = Math.Max((byte)0, Math.Min((byte)255, (byte)(*ptr + generator.Generate())));
                }
                ptr += offset;
            }
        }
Example #11
0
        public BankResponse processPayment(BankRequest request)
        {
            var seed          = _randomSeed.Generate();
            var transactionId = new DateTimeOffset().ToUnixTimeMilliseconds().ToString();

            // very dangerous, don't use it on production :D
            if (seed < 7 || request.CardNumber == "0000-0000-0000-0000")
            {
                return(new BankResponse {
                    id = transactionId,
                    successful = true,
                    message = "successful transaction",
                    statusCode = 1
                });
            }

            if (seed < 9)
            {
                return(new BankResponse {
                    id = transactionId,
                    successful = false,
                    message = "not enough credit to perform transaction",
                    statusCode = 3
                });
            }

            throw new System.Exception("Bank Service Unavailable");
        }
Example #12
0
        public ActionResult SessionManagement()
        {
            var siteCookie = GetSessionCookie();

            if (siteCookie != null)
            {
                ViewData["session_id"] = siteCookie.Value;
                return(View());
            }
            var sessionId     = _passwordHashProvidcer.Hash(Guid.NewGuid() + _randomNumberGenerator.GenerateLong().ToString(), _salt);
            var custom        = _passwordHashProvidcer.Hash(Guid.NewGuid() + _randomNumberGenerator.Generate().ToString(), _salt);
            var cookieName    = string.Format("{0}{1}", SessionCookieNamePrefix, custom);
            var sessionCookie = new HttpCookie(cookieName)
            {
                Value  = sessionId,
                Domain = Request.Url.Host,
                Path   = "~/good/",
                // Expires = End of the session,
                HttpOnly  = true,
                Shareable = false
            };

            Response.Cookies.Add(sessionCookie);
            ViewData["session_id"] = sessionId;
            return(View());
        }
Example #13
0
        public void Shuffle()
        {
            var cardList = _cards.ToArray();

            _cards.Clear();
            _cards = new Stack <ICard>(cardList.OrderBy(x => _randomNumberGenerator.Generate(cardList.Length)));
        }
Example #14
0
 public void CurrentPlayerPlay()
 {
     while (!_gameBoard.Play(CurrentPlayer.PlayCharacter, _randomNumberGenerator.Generate(), _randomNumberGenerator.Generate()))
     {
         ;
     }
 }
Example #15
0
 /// <summary>
 ///   Generates a random vector of observations from the current distribution.
 /// </summary>
 ///
 /// <param name="samples">The number of samples to generate.</param>
 /// <param name="result">The location where to store the samples.</param>
 ///
 /// <returns>A random vector of observations drawn from this distribution.</returns>
 ///
 public virtual double[][] Generate(int samples, double[][] result)
 {
     if (generator == null)
     {
         generator = new MetropolisHasting(Dimension, LogProbabilityDensityFunction);
     }
     return(generator.Generate(samples, result));
 }
Example #16
0
 /// <summary>
 ///   Generates a random vector of observations from the current distribution.
 /// </summary>
 ///
 /// <param name="samples">The number of samples to generate.</param>
 /// <param name="result">The location where to store the samples.</param>
 ///
 /// <returns>A random vector of observations drawn from this distribution.</returns>
 ///
 public virtual int[][] Generate(int samples, int[][] result)
 {
     if (generator == null)
     {
         generator = MetropolisHasting.Discrete(Dimension, this);
     }
     return(generator.Generate(samples, result));
 }
Example #17
0
 /// <summary>
 /// Generate random chromosome value.
 /// </summary>
 ///
 /// <remarks><para>Regenerates chromosome's value using random number generator.</para>
 /// </remarks>
 ///
 public override void Generate()
 {
     for (int i = 0; i < length; i++)
     {
         // generate next value
         val[i] = chromosomeGenerator.Generate();
     }
 }
 /// <summary>
 ///   Randomizes (initializes) the weights of
 ///   the network using a Gaussian distribution.
 /// </summary>
 ///
 public void Randomize()
 {
     foreach (ActivationLayer layer in network.Layers)
     {
         foreach (ActivationNeuron neuron in layer.Neurons)
         {
             for (int i = 0; i < neuron.Weights.Length; i++)
             {
                 neuron.Weights[i] = random.Generate();
             }
             if (UpdateThresholds)
             {
                 neuron.Threshold = random.Generate();
             }
         }
     }
 }
        public string[] Generate()
        {
            var codePegs = new string[4];

            for (int i = 0; i < 4; i++)
            {
                codePegs[i] = PossibleColors.Options[_randomNumberGenerator.Generate()];
            }
            return(codePegs);
        }
Example #20
0
 public void ShuffleDeck()
 {
     _currentCardIndex = 0;
     for (var i = 0; i < _cards.Length; ++i)
     {
         int j    = _randomNumberGenerator.Generate(0, _cards.Length);
         var temp = _cards[j];
         _cards[i] = _cards[j];
         _cards[j] = temp;
     }
 }
Example #21
0
        private Point3D CreateToolLocation(double size)
        {
            var position = _random.Generate(0, 1) * size;
            var side     = _random.Generate(0, 4);

            switch (side)
            {
            case 0:
                return(new Point3D(0, position, 0));

            case 1:
                return(new Point3D(size, position, 0));

            case 2:
                return(new Point3D(position, 0, 0));

            default:
                return(new Point3D(position, size, 0));
            }
        }
Example #22
0
        /// <summary>
        /// Mutation operator.
        /// </summary>
        ///
        /// <remarks><para>The method performs chromosome's mutation, adding random number
        /// to chromosome's gene or multiplying the gene by random number. These random
        /// numbers are generated with help of <see cref="mutationMultiplierGenerator">mutation
        /// multiplier</see> and <see cref="mutationAdditionGenerator">mutation
        /// addition</see> generators.</para>
        ///
        /// <para>The exact type of mutation applied to the particular gene
        /// is selected randomly each time and depends on <see cref="MutationBalancer"/>.
        /// Before mutation is done a random number is generated in [0, 1] range - if the
        /// random number is smaller than <see cref="MutationBalancer"/>, then multiplication
        /// mutation is done, otherwise addition mutation.
        /// </para></remarks>
        ///
        public override void Mutate()
        {
            int mutationGene = Generator.Random.Next(length);

            if (Generator.Random.NextDouble() < mutationBalancer)
            {
                val[mutationGene] *= mutationMultiplierGenerator.Generate();
            }
            else
            {
                val[mutationGene] += mutationAdditionGenerator.Generate();
            }
        }
        /// <summary>
        ///   Creates a rows-by-cols matrix with random data.
        /// </summary>
        ///
        public static T[][] Random <T>(int rows, int cols,
                                       IRandomNumberGenerator <T> generator, T[][] result = null)
        {
            if (result == null)
            {
                result = Jagged.Create <T>(rows, cols);
            }

            for (int i = 0; i < rows; i++)
            {
                result[i] = generator.Generate(cols);
            }
            return(result);
        }
Example #24
0
 /// <summary>
 /// 获取随机长度
 /// </summary>
 private int GetRandomLength(int maxLength)
 {
     return(_random.Generate(1, maxLength));
 }
 /// <summary>
 /// 获取随机长度
 /// </summary>
 /// <param name="maxLength">最大值(默认为int.MaxValue)</param>
 /// <param name="minLength">最小值(默认为0)</param>
 /// <returns></returns>
 private int GetRandomLength(int maxLength = int.MaxValue, int minLength = 1)
 {
     return(_random.Generate(minLength, maxLength));
 }
Example #26
0
        /// <summary>
        /// 生成随机布尔值
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool GenerateBool()
        {
            var random = _random.Generate(1, 100);

            if (random % 2 == 0)
            {
                return(false);
            }
            return(true);
        }
Example #27
0
 /// <summary>
 /// Randomize neuron.
 /// </summary>
 ///
 /// <remarks>
 ///   Initialize neuron's weights with random values specified
 ///   by the <see cref="RandGenerator"/>.</remarks>
 ///
 public virtual void Randomize()
 {
     rand.Generate(weights.Length, weights);
 }
Example #28
0
 public static void Generate(this IRandomNumberGenerator rng, byte[] data) =>
 rng.Generate(new ArraySegment <byte>(data));
Example #29
0
 public static void Generate(this IRandomNumberGenerator rng, byte[] data, int offset, int count) =>
 rng.Generate(new ArraySegment <byte>(data, offset, count));
Example #30
0
 public static byte[] Generate(this IRandomNumberGenerator rng, int howmuch)
 {
     byte[] data = new byte[howmuch];
     rng.Generate(data);
     return(data);
 }