NextDouble() публичный Метод

Returns a random number between 0.0 and 1.0.
public NextDouble ( ) : double
Результат double
Пример #1
0
        public void Decimal_Rnd()
        {
            BVector        d = new BVector();
            decimal        value;
            const decimal  maxValue = decimal.MaxValue;
            const decimal  minValue = decimal.MinValue;
            var            rnd      = new CryptoRandom();
            List <decimal> values   = new List <decimal>();

            // number of items to add per bit
            int itemsCount = 1_000;

            for (int i = 0; i < itemsCount; i++)
            {
                // add positive
                value = (decimal)rnd.NextDouble() * maxValue;
                d.Add(value);
                values.Add(value);
                d.Add1(false);

                // add negative
                value = (decimal)rnd.NextDouble() * minValue;
                d.Add(value);
                values.Add(value);
                d.Add1(true);
            }

            for (int i = 0; i < itemsCount; i++)
            {
                value = d.GetDecimal();
                Assert.AreEqual(values[i], value);
                Assert.AreEqual(i % 2 != 0, d.Get1());
            }
        }
Пример #2
0
        public void NextDouble()
        {
            var rng = new CryptoRandom();

            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            Assert.DoesNotThrow(() => rng.NextDouble());
            Assert.DoesNotThrow(() => rng.NextDouble());
            // ReSharper restore ReturnValueOfPureMethodIsNotUsed
        }
Пример #3
0
        private static double GetRandomNormalDistributedWithGivenMeanAndStdev(CryptoRandom rand, double mean, double stddev, int precision)
        {
            //https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
            //http://stackoverflow.com/questions/218060/random-gaussian-variables

            double u1              = rand.NextDouble();
            double u2              = rand.NextDouble();
            double randStdNormal   = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
            double randNormal      = mean + stddev * randStdNormal;
            double finalSampledVal = Math.Round(randNormal, precision);

            return(finalSampledVal);
        }
Пример #4
0
        public void Sample()
        {
            var random = new CryptoRandom();
            double next = -1.0;
            Assert.DoesNotThrow(() => next = random.NextDouble());
            Assert.That(next, Is.GreaterThanOrEqualTo(0.0));
            Assert.That(next, Is.LessThanOrEqualTo(1.0));

            next = -1.0;
            Assert.DoesNotThrow(() => next = random.NextDouble());
            Assert.That(next, Is.GreaterThanOrEqualTo(0.0));
            Assert.That(next, Is.LessThanOrEqualTo(1.0));
        }
Пример #5
0
        public int act(SimpleDatum sd, SimpleDatum sdClip, out float[] rgfAprob)
        {
            List<Datum> rgData = new List<Datum>();
            rgData.Add(new Datum(sd));
            double dfLoss;
            float fRandom = (float)m_random.NextDouble(); // Roll the dice.
            List<Datum> rgClip = null;

            if (sdClip != null)
            {
                rgClip = new List<Datum>();
                rgClip.Add(new Datum(sdClip));
            }

            m_memData.AddDatumVector(rgData, rgClip, 1, true, true);
            m_bSkipLoss = true;
            BlobCollection<T> res = m_net.Forward(out dfLoss);
            m_bSkipLoss = false;

            rgfAprob = null;

            for (int i = 0; i < res.Count; i++)
            {
                if (res[i].type != BLOB_TYPE.LOSS)
                {
                    int nStart = 0;
                    // When using recurrent learning, only act on the last outputs.
                    if (m_nRecurrentSequenceLength > 1 && res[i].num > 1)
                    {
                        int nCount = res[i].count();
                        int nOutput = nCount / res[i].num;
                        nStart = nCount - nOutput;

                        if (nStart < 0)
                            throw new Exception("The start must be zero or greater!");
                    }

                    rgfAprob = Utility.ConvertVecF<T>(res[i].update_cpu_data(), nStart);
                    break;
                }
            }

            if (rgfAprob == null)
                throw new Exception("Could not find a non-loss output!  Your model should output the loss and the action probabilities.");

            // Select the action from the probability distribution.
            float fSum = 0;
            for (int i = 0; i < rgfAprob.Length; i++)
            {
                fSum += rgfAprob[i];

                if (fRandom < fSum)
                    return i;
            }

            if (rgfAprob.Length == 1)
                return 1;

            return rgfAprob.Length - 1;
        }
        private void testRandom(Log log, CryptoRandom.METHOD method, int nBuckets)
        {
            PreTest.Init();

            BucketCollection col  = new BucketCollection(0, 1, nBuckets);
            CryptoRandom     rand = new CryptoRandom(method, Guid.NewGuid().GetHashCode());
            int nTotal            = 1000000;

            log.WriteLine("Testing (" + nBuckets.ToString() + ") " + method.ToString());

            for (int i = 0; i < nTotal; i++)
            {
                double df = rand.NextDouble();
                col.Add(df);
            }

            string        str  = "";
            List <double> rgdf = new List <double>();

            for (int i = 0; i < nBuckets; i++)
            {
                double dfPct = col[i].Count / (double)nTotal;
                str += dfPct.ToString("P");
                str += ", ";
                rgdf.Add(dfPct);
            }

            str = str.TrimEnd(',', ' ');

            log.WriteLine(method.ToString() + " =>> " + str);

            double dfStdev = stdDev(rgdf, false);

            log.WriteLine(method.ToString() + " stdev = " + dfStdev.ToString());
        }
Пример #7
0
        private int getAction(int nIteration, SimpleDatum sd, SimpleDatum sdClip, int nActionCount, TRAIN_STEP step)
        {
            if (step == TRAIN_STEP.NONE)
            {
                switch (m_state)
                {
                case STATE.EXPLORING:
                    return(m_random.Next(nActionCount));

                case STATE.TRAINING:
                    if (m_dfExplorationRate > m_dfEpsEnd)
                    {
                        m_dfExplorationRate -= m_dfEpsDelta;
                    }

                    if (m_random.NextDouble() < m_dfExplorationRate)
                    {
                        return(m_random.Next(nActionCount));
                    }
                    break;
                }
            }

            return(m_brain.act(sd, sdClip, nActionCount));
        }
Пример #8
0
        public Weapon GenerateWeapon(int itemLevel, ItemClass itemClass)
        {
            Weapon result = null;

            ItemIcon     itemIcon     = this.GenerateItemIcon(itemClass, ItemType.Weapon);
            string       itemName     = this.GenerateItemName(itemClass, EqType.Weapon);
            int          goldValue    = this.GenerateItemGoldValue(itemLevel);
            double       itemWeight   = Math.Round(CryptoRandom.NextDouble(0, 5), 2, MidpointRounding.AwayFromZero);
            ItemFeatures itemFeatures = new ItemFeatures();

            itemFeatures.EnableFeatures(ItemFeaturesType.IsDeleteAble, ItemFeaturesType.IsEquipAble,
                                        ItemFeaturesType.IsInfoAble, ItemFeaturesType.IsRepairAble, ItemFeaturesType.IsSellAble,
                                        ItemFeaturesType.IsUpgradeAble);

            switch (itemClass)
            {
            case ItemClass.Magic:
            {
                result = new Weapon(itemClass, ItemType.Weapon, ItemSubType.None, itemIcon, EqType.Weapon,
                                    itemFeatures, itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                break;
            }

            case ItemClass.Melle:
            {
                result = new Weapon(itemClass, ItemType.Weapon, ItemSubType.None, itemIcon, EqType.Weapon,
                                    itemFeatures, itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase));

                break;
            }

            case ItemClass.Ranged:
            {
                result = new Weapon(itemClass, ItemType.Weapon, ItemSubType.None, itemIcon, EqType.Weapon,
                                    itemFeatures, itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                    StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                break;
            }
            }

            return(result);
        }
Пример #9
0
        public void Run(ModuleDefMD moduleDefMd)
        {
            _moduleDefMd            = moduleDefMd;
            Console.ForegroundColor = ConsoleColor.Green;
            Logger.Push($"Running {nameof(Mutation)}");
            Console.ForegroundColor = ConsoleColor.Gray;

            using var cryptoRandom = new CryptoRandom();
            foreach (var typeDef in moduleDefMd.GetTypes())
            {
                var listMethod = new List <MethodDef>(); // List of proxy methods to be added in typeDef
                foreach (var methodDef in typeDef.Methods.Where(x => x.HasBody))
                {
                    var instructions = methodDef.Body.Instructions;
                    for (var i = 0; i < instructions.Count; i++)
                    {
                        if (instructions[i].IsLdcI4() && IsSafe(instructions.ToList(), i))
                        {
                            MethodDef refMethod = null;
                            int       operand   = instructions[i].GetLdcI4Value();
                            instructions[i].OpCode = OpCodes.Ldc_R8;
                            switch (cryptoRandom.Next(0, 3))
                            {
                            case 0:
                                refMethod = GenerateRefMethod("Floor");
                                instructions[i].Operand = Convert.ToDouble(operand + cryptoRandom.NextDouble());
                                break;

                            case 1:
                                refMethod = GenerateRefMethod("Sqrt");
                                instructions[i].Operand = Math.Pow(Convert.ToDouble(operand), 2);
                                break;

                            case 2:
                                refMethod = GenerateRefMethod("Round");
                                instructions[i].Operand = Convert.ToDouble(operand);
                                break;
                            }

                            instructions.Insert(i + 1, OpCodes.Call.ToInstruction(refMethod));
                            instructions.Insert(i + 2, OpCodes.Conv_I4.ToInstruction());
                            i += 2;
                            listMethod.Add(refMethod);
                        }
                    }

                    methodDef.Body.SimplifyMacros(methodDef.Parameters);
                }

                foreach (var method in listMethod)
                {
                    typeDef.Methods.Add(method);
                }
            }
        }
Пример #10
0
        public void NextDouble_Generates_Random_Number_Within_Range()
        {
            // arrange
            var cryptoRandom = new CryptoRandom();

            // act
            var result = cryptoRandom.NextDouble();

            // assert
            result.Should().BeInRange(0.0, 1.0);
        }
Пример #11
0
        private float getRandom(float fMin, float fMax)
        {
            float  fRange = fMax - fMin;
            double dfVal  = m_random.NextDouble();

            return(fMin + (float)(fRange * dfVal));
        }
Пример #12
0
        public int act(SimpleDatum sd, out float[] rgfAprob)
        {
            List <Datum> rgData = new List <Datum>();

            rgData.Add(new Datum(sd));
            double dfLoss;
            float  fRandom = (float)m_random.NextDouble(); // Roll the dice.

            m_memData.AddDatumVector(rgData, 1, true, true);
            m_bSkipLoss = true;
            BlobCollection <T> res = m_net.Forward(out dfLoss);

            m_bSkipLoss = false;

            rgfAprob = null;

            for (int i = 0; i < res.Count; i++)
            {
                if (res[i].type != Blob <T> .BLOB_TYPE.LOSS)
                {
                    rgfAprob = Utility.ConvertVecF <T>(res[i].update_cpu_data());
                    break;
                }
            }

            if (rgfAprob == null)
            {
                throw new Exception("Could not find a non-loss output!  Your model should output the loss and the action probabilities.");
            }

            // Select the action from the probability distribution.
            float fSum = 0;

            for (int i = 0; i < rgfAprob.Length; i++)
            {
                fSum += rgfAprob[i];

                if (fRandom < fSum)
                {
                    return(i);
                }
            }

            if (rgfAprob.Length == 1)
            {
                return(1);
            }

            return(rgfAprob.Length - 1);
        }
Пример #13
0
        private int[] getSamplesProportional(CryptoRandom random, int nCount)
        {
            int[] rgIdx = new int[nCount];

            for (int i = 0; i < nCount; i++)
            {
                double dfRand = random.NextDouble();
                double dfSum1 = m_ItSum.sum(0, m_mem.Count - 1);
                double dfMass = dfRand * dfSum1;
                int    nIdx   = m_ItSum.find_prefixsum_idx((float)dfMass);
                rgIdx[i] = nIdx;
            }

            return(rgIdx);
        }
Пример #14
0
        private int getLastPrediction(float[] rgData, BucketCollection rgVocabulary)
        {
            int nIdx = m_nVocabSize - 1;

            // If no temperature, return directly the character with the best score
            if (m_dfTemperature == 0)
            {
                nIdx = ArgMax(rgData, 0, m_nVocabSize);
            }
            else
            {
                // Otherwise, compute the probabilities with the temperature and select the character according to the probabilities.
                double[] rgAccumulatedProba = new double[m_nVocabSize];
                double[] rgProba            = new double[m_nVocabSize];
                double   dfExpoSum          = 0;

                for (int i = 0; i < m_nVocabSize; i++)
                {
                    // The max value is subtracted for numerical stability
                    rgProba[i] = Math.Exp((rgData[i] - (m_nVocabSize - 1)) / m_dfTemperature);
                    dfExpoSum += rgProba[i];
                }

                rgProba[0]           /= dfExpoSum;
                rgAccumulatedProba[0] = rgProba[0];

                double dfRandom = m_random.NextDouble();

                for (int i = 1; i < rgProba.Length; i++)
                {
                    // Return the first index for which the accumulated probability is bigger than the random number.
                    if (rgAccumulatedProba[i - 1] > dfRandom)
                    {
                        return(i - 1);
                    }

                    rgProba[i]           /= dfExpoSum;
                    rgAccumulatedProba[i] = rgAccumulatedProba[i - 1] + rgProba[i];
                }
            }

            if (nIdx < 0 || nIdx > rgVocabulary.Count)
            {
                throw new Exception("Invalid index - out of the vocabulary range of [0," + rgVocabulary.Count.ToString() + "]");
            }

            return(nIdx);
        }
Пример #15
0
        private LabelSet getLabelSet(IMGDB_LABEL_SELECTION_METHOD labelSelectionMethod)
        {
            double dfBoostTotal = m_dfLabelBoostTotal;
            Dictionary <int, double> rgBoosts = m_rgLabelBoosts;
            int nIdx;

            if ((labelSelectionMethod & IMGDB_LABEL_SELECTION_METHOD.BOOST) != IMGDB_LABEL_SELECTION_METHOD.BOOST)
            {
                nIdx = m_random.Next(m_rgLabelSetWithData.Count);
                return(m_rgLabelSetWithData[nIdx]);
            }


            //---------------------------------------------
            //  Handle Label Sets with label boost.
            //---------------------------------------------
            else
            {
                double dfVal   = m_random.NextDouble() * dfBoostTotal;
                double dfTotal = 0;

                nIdx = m_rgLabelSet.Count - 1;

                for (int i = 0; i < m_rgLabelSet.Count; i++)
                {
                    int nLabel = m_rgLabelSet[i].Label.ActiveLabel;

                    if (rgBoosts != null && rgBoosts.ContainsKey(nLabel))
                    {
                        dfTotal += (double)rgBoosts[nLabel];
                    }
                    else
                    {
                        dfTotal += 1;
                    }

                    if (dfTotal >= dfVal)
                    {
                        nIdx = i;
                        break;
                    }
                }

                return(m_rgLabelSet[nIdx]);
            }
        }
Пример #16
0
        public void ApplyRune()
        {
            if (ItemToImprove == null || Rune == null)
            {
                return;
            }

            var rune = Rune;

            rune.Owner.Inventory.RemoveItem(rune.PlayerItem, 1);
            Crafter.MoveItem(rune.Guid, -1);

            foreach (var effect in rune.Effects.OfType <EffectInteger>())
            {
                var existantEffect = GetEffectToImprove(effect);

                double criticalSuccess, neutralSuccess, criticalFailure;
                GetChances(existantEffect, effect, out criticalSuccess, out neutralSuccess, out criticalFailure);

                var rand       = new CryptoRandom();
                var randNumber = (int)(rand.NextDouble() * 100);

                if (randNumber <= criticalSuccess)
                {
                    BoostEffect(effect);

                    OnRuneApplied(CraftResultEnum.CRAFT_SUCCESS, MagicPoolStatus.UNMODIFIED);
                }
                else if (randNumber <= criticalSuccess + neutralSuccess)
                {
                    BoostEffect(effect);
                    int residual = DeBoostEffect(effect);

                    OnRuneApplied(CraftResultEnum.CRAFT_SUCCESS, GetMagicPoolStatus(residual));
                }
                else
                {
                    int residual = DeBoostEffect(effect);

                    OnRuneApplied(CraftResultEnum.CRAFT_FAILED, GetMagicPoolStatus(residual));
                }
            }

            ItemToImprove.PlayerItem.Invalidate();
        }
Пример #17
0
        public int act(SimpleDatum sd, out float fAprob)
        {
            List <Datum> rgData = new List <Datum>();

            rgData.Add(new Datum(sd));
            double dfLoss;

            m_memData.AddDatumVector(rgData, 1, true, true);
            m_bSkipLoss = true;
            BlobCollection <T> res = m_net.Forward(out dfLoss);

            m_bSkipLoss = false;
            float[] rgfAprob = null;

            for (int i = 0; i < res.Count; i++)
            {
                if (res[i].type != Blob <T> .BLOB_TYPE.LOSS)
                {
                    rgfAprob = Utility.ConvertVecF <T>(res[i].update_cpu_data());
                    break;
                }
            }

            if (rgfAprob == null)
            {
                throw new Exception("Could not find a non-loss output!  Your model should output the loss and the action probabilities.");
            }

            if (rgfAprob.Length != 1)
            {
                throw new Exception("The simple policy gradient only supports a single data output!");
            }

            fAprob = rgfAprob[0];

            // Roll the dice!
            if (m_random.NextDouble() < (double)fAprob)
            {
                return(0);
            }
            else
            {
                return(1);
            }
        }
Пример #18
0
        private void OnGeneratingResults(IFight obj)
        {
            if (Owner.Fighter.Fight is FightPvM fightPvM && fightPvM == obj && !fightPvM.IsPvMArenaFight && Owner.Fighter.HasWin() && Owner.Fighter.HasState((int)SpellStatesEnum.CHERCHEUR_DAMES_2))
            {
                if (Owner.Fighter.Team.Fighters.Any(x => x.Loot.Items.Any(y => y.Key == (int)ItemIdEnum.PIERRE_DAME_PLEINE_7010)))
                {
                    return;
                }

                var highestLevel = Owner.Fighter.OpposedTeam.Fighters.Max(x => x.Level);

                if (highestLevel <= Power)
                {
                    var rand = new CryptoRandom();

                    if (rand.NextDouble() * 100 <= Probability)
                    {
                        if (Owner.Inventory.RemoveItem(this, 1) <= 0)
                        {
                            return;
                        }

                        var fullStone = ItemManager.Instance.CreatePlayerItem(Owner, (int)ItemIdEnum.PIERRE_DAME_PLEINE_7010, 1) as SoulStoneFilled;

                        if (fullStone == null)
                        {
                            return;
                        }

                        fullStone.SetMonsterGroup(fightPvM.DefendersTeam.Fighters.OfType <MonsterFighter>().Select(x => x.Monster));

                        Owner.Inventory.AddItem(fullStone);
                        // display purpose
                        Owner.Fighter.Loot.AddItem(new DroppedItem(fullStone.Template.Id, 1)
                        {
                            IgnoreGeneration = true
                        });
                    }
                }
            }
        }
Пример #19
0
//        [Repeat(10)]
        public void SanityCheckDuplicates()
        {
            const int distributionBuckets = 100;
            const int numbersToSample     = 1000000;

            var mathRandom  = new Random();
            var mathResults = new List <double>();

            for (int i = 0; i < numbersToSample; i++)
            {
                mathResults.Add(mathRandom.NextDouble());
            }
            mathResults.Sort();
            var mathDistribution      = GetDistribution(mathResults, distributionBuckets);
            var mathDistributedValues = mathDistribution.Values.OrderByDescending(x => x).ToList();

            var rngRandom  = new CryptoRandom();
            var rngResults = new List <double>();

            for (int i = 0; i < numbersToSample; i++)
            {
                rngResults.Add(rngRandom.NextDouble());
            }
            rngResults.Sort();
            var rngDistribution      = GetDistribution(rngResults, distributionBuckets);
            var rngDistributedValues = rngDistribution.Values.OrderByDescending(x => x).ToList();

            for (int i = 0; i < distributionBuckets; i++)
            {
                Console.WriteLine("{0,2}: {1,20} {2,20}", i, mathDistributedValues[i], rngDistributedValues[i]);
            }

//            var mathMin = mathDistribution.Values.Min();
//            var mathMax = mathDistribution.Values.Min();
//
//            var rngMin = rngDistribution.Values.Min();
//            var rnghMax = rngDistribution.Values.Min();
//
//            Assert.GreaterOrEqual(rngMin, mathMin);
//            Assert.LessOrEqual(rnghMax, mathMax);
        }
Пример #20
0
        private int argmax(float[] rgfAprob)
        {
            double fMax = -float.MaxValue;
            int    nIdx = 0;

            for (int i = 0; i < rgfAprob.Length; i++)
            {
                if (rgfAprob[i] == fMax)
                {
                    if (m_random.NextDouble() > 0.5)
                    {
                        nIdx = i;
                    }
                }
                else if (fMax < rgfAprob[i])
                {
                    fMax = rgfAprob[i];
                    nIdx = i;
                }
            }

            return(nIdx);
        }
Пример #21
0
        private float randomUniformValue(float fMin, float fMax)
        {
            fMin = (float)Math.Round(fMin, 5);
            fMax = (float)Math.Round(fMax, 5);

            m_log.CHECK_LE(fMin, fMax, "The min mumst be <= the max!");

            if (fMin == 0 && fMax == 0)
            {
                return(0.0f);
            }
            else if (fMin == 1 && fMax == 1)
            {
                return(1.0f);
            }
            else
            {
                double dfRandom = m_random.NextDouble();
                float  fRange   = fMax - fMin;

                return((float)(dfRandom * fRange) + fMin);
            }
        }
Пример #22
0
        private EffectInteger GetEffectToDown(EffectInteger runeEffect)
        {
            var effectToImprove = GetEffectToImprove(runeEffect);
            // recherche de jet exotique
            var exoticEffect = ItemEffects.Where(x => IsExotic(x) && x != effectToImprove).RandomElementOrDefault();

            if (exoticEffect != null)
            {
                return(exoticEffect);
            }

            // recherche de jet overmax
            var overmaxEffect = ItemEffects.Where(x => IsOverMax(x, runeEffect) && x != effectToImprove).RandomElementOrDefault();

            if (overmaxEffect != null)
            {
                return(overmaxEffect);
            }

            var rand = new CryptoRandom();

            foreach (var effect in ItemEffects.ShuffleLinq().Where(x => x != effectToImprove))
            {
                if (EffectManager.Instance.GetEffectPower(effect) - EffectManager.Instance.GetEffectPower(runeEffect) < MAX_STAT_POWER)
                {
                    continue;
                }

                if (rand.NextDouble() <= EffectManager.Instance.GetEffectPower(runeEffect) / Math.Abs(EffectManager.Instance.GetEffectBasePower(effect)))
                {
                    return(effect);
                }
            }

            return(ItemEffects.FirstOrDefault(x => x != effectToImprove));
        }
Пример #23
0
        public ConsumeableItem GenerateConsumeableItem(ItemType itemType, ItemSubType itemSubType)
        {
            ConsumeableItem result = null;

            int      goldValue;
            int      boost;
            ItemIcon itemIcon = this.GenerateItemIcon(ItemClass.Normal, itemType, EqType.None, itemSubType);

            itemIcon.Rarity = (int)ItemRarity.None;
            ItemFeatures itemFeatures = new ItemFeatures();

            itemFeatures.EnableFeatures(ItemFeaturesType.IsDeleteAble, ItemFeaturesType.IsInfoAble, ItemFeaturesType.IsSellAble, ItemFeaturesType.IsEatAble);

            switch (itemType)
            {
            case ItemType.Potion:
            {
                switch (itemSubType)
                {
                case ItemSubType.Potion_Armor:
                {
                    goldValue = CryptoRandom.Next(200, 500);
                    boost     = CryptoRandom.Next(8, 15);
                    result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                    itemFeatures, "Armor Potion", string.Empty, goldValue, 0.5);
                    break;
                }

                case ItemSubType.Potion_Dexterity:
                {
                    goldValue = CryptoRandom.Next(200, 500);
                    boost     = CryptoRandom.Next(8, 15);
                    result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                    itemFeatures, "Dexterity Potion", string.Empty, goldValue, 0.5);
                    break;
                }

                case ItemSubType.Potion_Health:
                {
                    goldValue = 50;
                    boost     = 60;
                    result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                    itemFeatures, "Health Potion", string.Empty, goldValue, 0.5);
                    break;
                }

                case ItemSubType.Potion_Intelligence:
                {
                    goldValue = CryptoRandom.Next(200, 500);
                    boost     = CryptoRandom.Next(8, 15);
                    result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                    itemFeatures, "Intelligence Potion", string.Empty, goldValue, 0.5);
                    break;
                }

                case ItemSubType.Potion_Mana:
                {
                    goldValue = 50;
                    boost     = 60;
                    result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                    itemFeatures, "Mana Potion", string.Empty, goldValue, 0.5);
                    break;
                }

                case ItemSubType.Potion_Strength:
                {
                    goldValue = CryptoRandom.Next(200, 500);
                    boost     = CryptoRandom.Next(8, 15);
                    result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                    itemFeatures, "Armor Potion", string.Empty, goldValue, 0.5);
                    break;
                }

                default:
                {
                    break;
                }
                }
                break;
            }

            case ItemType.Food:
            {
                boost     = CryptoRandom.Next(20, 50);
                goldValue = CryptoRandom.Next(20, 60);
                result    = new ConsumeableItem(boost, ItemClass.Normal, itemType, itemSubType, itemIcon,
                                                itemFeatures, "Food" +
                                                "", string.Empty, goldValue, CryptoRandom.NextDouble(0.3, 1));
                break;
            }
            }

            return(result);
        }
Пример #24
0
        public void Decraft()
        {
            m_decrafting = true;
            var results = new Dictionary <PlayerTradeItem, DecraftResult>();

            foreach (var item in Trader.Items.OfType <PlayerTradeItem>())
            {
                var result = new DecraftResult(item);
                results.Add(item, result);
                for (int i = 0; i < item.Stack; i++)
                {
                    RuneManager.Instance.RegisterDecraft(item.Template);
                    var coeff = RuneManager.Instance.GetDecraftCoefficient(item.Template);

                    foreach (var effect in item.Effects.OfType <EffectInteger>())
                    {
                        var runes = RuneManager.Instance.GetEffectRunes(effect.EffectId);

                        if (runes.Length <= 0)
                        {
                            continue;
                        }

                        var prop = coeff * effect.Value * Math.Min(2 / 3d, 1.5 * item.Template.Level * item.Template.Level / Math.Pow(EffectManager.Instance.GetEffectBasePower(effect), 5 / 4d));

                        var random = new CryptoRandom();
                        prop *= random.NextDouble() * 0.2 + 0.9;

                        var amount = (int)Math.Floor(prop);
                        if (random.NextDouble() < prop - Math.Floor(prop))
                        {
                            amount++;
                        }

                        var rune = runes.OrderBy(x => x.Amount).First();

                        var runeAmount = (int)Math.Floor((double)amount / rune.Amount);

                        if (result.Runes.ContainsKey(rune.Item))
                        {
                            result.Runes[rune.Item] += runeAmount;
                        }
                        else
                        {
                            result.Runes.Add(rune.Item, runeAmount);
                        }
                    }

                    if (!result.MinCoeff.HasValue || coeff < result.MinCoeff)
                    {
                        result.MinCoeff = coeff;
                    }
                    if (!result.MaxCoeff.HasValue || coeff > result.MaxCoeff)
                    {
                        result.MaxCoeff = coeff;
                    }
                }
            }
            InventoryHandler.SendDecraftResultMessage(Character.Client,
                                                      results.Select(x => new DecraftedItemStackInfo(x.Key.Guid, (float)(x.Value.MinCoeff ?? 0.5), (float)(x.Value.MaxCoeff ?? 0.5), x.Value.Runes.Select(y => (short)y.Key.Id), x.Value.Runes.Select(y => y.Value))));

            foreach (PlayerTradeItem item in results.Keys)
            {
                Character.Inventory.RemoveItem(item.PlayerItem, (int)item.Stack);
                Trader.MoveItem(item.Guid, 0);
            }

            foreach (var group in results.Values.SelectMany(x => x.Runes).GroupBy(x => x.Key))
            {
                var rune   = group.Key;
                var amount = group.Sum(x => x.Value);

                Character.Inventory.AddItem(rune, amount);
            }
            m_decrafting = false;
        }
Пример #25
0
        /// <summary>
        /// Adds a random value to the specified BVector
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static object WriteRandomValue(BVector d)
        {
            int           stringLen = 0;
            StringBuilder sb;
            string        unicodeChars;

            object result    = null;
            var    rnd       = new CryptoRandom();
            int    valueType = rnd.Next(12);
            bool   nullable  = rnd.Next(2) == 1;

            d.Add1(nullable);
            d.Add8((byte)valueType);

            switch (valueType)
            {
            case 0:     // int
                result = rnd.Next(int.MinValue, int.MaxValue);
                if (nullable)
                {
                    d.Add((int?)result);
                }
                else
                {
                    d.Add((int)result);
                }
                break;

            case 1:     // long
                result = rnd.NextLong(long.MinValue, long.MaxValue);
                if (nullable)
                {
                    d.Add((long?)result);
                }
                else
                {
                    d.Add((long)result);
                }
                break;

            case 2:     // short
                result = (short)rnd.Next(short.MinValue, short.MaxValue);
                if (nullable)
                {
                    d.Add((short?)result);
                }
                else
                {
                    d.Add((short)result);
                }
                break;

            case 3:     // byte
                result = (byte)rnd.Next(byte.MinValue, byte.MaxValue);
                if (nullable)
                {
                    d.Add((byte?)result);
                }
                else
                {
                    d.Add((byte)result);
                }
                break;

            case 4:     // string (unicode)
                stringLen    = rnd.Next(0, 1000);
                sb           = new StringBuilder();
                unicodeChars = GetUnicodeCharacters();
                for (int i = 0; i < stringLen; i++)
                {
                    int index = rnd.Next(unicodeChars.Length);
                    sb.Append(unicodeChars[index]);
                }
                result = sb.ToString();
                d.Add((string)result);
                break;

            case 5:     // ascii
                stringLen = rnd.Next(0, 1000);
                sb        = new StringBuilder();
                for (int i = 0; i < stringLen; i++)
                {
                    int ascii = rnd.Next(255);
                    sb.Append((char)ascii);
                }
                result = sb.ToString();
                d.AddAscii((string)result);
                break;

            case 6:     // DateTime
                result = new DateTime(rnd.NextLong(DateTime.MinValue.Ticks, DateTime.MaxValue.Ticks));
                if (nullable)
                {
                    d.Add((DateTime?)result);
                }
                else
                {
                    d.Add((DateTime)result);
                }
                break;

            case 7:     // decimal
                result = (decimal)rnd.NextDouble() * decimal.MaxValue;
                if (nullable)
                {
                    d.Add((decimal?)result);
                }
                else
                {
                    d.Add((decimal)result);
                }
                break;

            case 8:     // double
                result = rnd.NextDouble() * double.MaxValue;
                if (nullable)
                {
                    d.Add((double?)result);
                }
                else
                {
                    d.Add((double)result);
                }
                break;

            case 9:     // bool
                result = rnd.Next(2) == 1;
                d.Add1((bool)result);
                break;

            case 10:     // TimeSpan
                result = new TimeSpan(rnd.NextLong(TimeSpan.MinValue.Ticks, TimeSpan.MaxValue.Ticks));
                d.Add((TimeSpan)result);
                break;

            case 11:     // byte[]
                result = rnd.NextBytes(rnd.Next(1000));
                d.Add((byte[])result);
                break;
            }

            return(result);
        }
Пример #26
0
		static void Main(string[] args)
		{
			const bool SEEDED_TEST = false;
			const long ITER = 10_000_000L * 2L;
			const bool IS_SEQUENTIAL = false;
			const bool IS_PARALLEL = true;

			if (SEEDED_TEST)
			{
				var seedkey = new byte[CryptoRandom.Params.Seeded.SEEDKEY_SIZE];
				var seeded = new CryptoRandom(seedkey);

				Span<byte> data = new byte[256];

				seeded.Reseed(seedkey);
				seeded.NextBytes(data);
				Convert.ToHexString(data).Dump();

				data.Clear();
				//seeded = new SeededCryptoRandomImpl(seedkey); 
				seeded.Reseed(seedkey);
				for (int i = 0; i < data.Length; ++i)
				{
					seeded.NextBytes(data.Slice(i, 1));
					Convert.ToHexString(data.Slice(0, i + 1)).Dump(); Console.WriteLine("====================");
				}

				return;
			}
			var sw = new Stopwatch();

            $".NET: [{Environment.Version}]".Dump();
			$"{nameof(Environment.ProcessorCount)}: {Environment.ProcessorCount}".Dump();
			$"{nameof(CryptoRandom.Params.RNG.BYTE_CACHE_SIZE)}: {CryptoRandom.Params.RNG.BYTE_CACHE_SIZE}".Dump();
			$"{nameof(CryptoRandom.Params.RNG.REQUEST_CACHE_LIMIT)}: {CryptoRandom.Params.RNG.REQUEST_CACHE_LIMIT}".Dump();
			$"{nameof(TestStruct)} Size: {Utils.StructSizer<TestStruct>.Size}\n".Dump();


			for (int _ = 0; _ < 4; ++_)
			{
				Guid g = default;
				cr.Next(ref g);
				g.Dump();
			}
			"".Dump();
			//return;
			const int REPS = 5;


			IS_SEQUENTIAL.Dump(nameof(IS_SEQUENTIAL));
			IS_PARALLEL.Dump(nameof(IS_PARALLEL));

			for (int j = 0; j < REPS; ++j)
			{
				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						var data = default(TestStruct);
						var span = Utils.AsSpan(ref data);
						cr.NextBytes(span);
					});
					sw.Stop();
					$"{sw.Elapsed} Utils.AsSpan(ref data); cr.NextBytes(span);".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						var data = default(TestStruct);
						cr.Next(ref data);
					});
					sw.Stop();
					$"{sw.Elapsed} cr.Next(ref data);".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						var data = default(TestStruct);
						CryptoRandom.Shared.Next(ref data);
					});
					sw.Stop();
					$"{sw.Elapsed} CryptoRandom.Shared.Next(ref data);".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.NextGuid();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.NextGuid();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.Next<Guid>();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.Next<Guid>();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						Guid.NewGuid();
					});
					sw.Stop();
					$"{sw.Elapsed} Guid.NewGuid();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.SqlServerGuid();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.SqlServerGuid();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.Next();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.Next();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.NextDouble();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.NextDouble();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.NextSingle();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.NextSingle();".Dump();
				}
				"".Dump();
			}// REPS
		}//Main()
Пример #27
0
        private float getRandom(float fMin, float fMax, float fTotal = 256)
        {
            float  fRange = fMax - fMin;
            double dfVal  = m_random.NextDouble();
            double dfPct  = ((fMin + (float)(fRange * dfVal)) / fTotal);

            return(1.0f + (float)dfPct);
        }
Пример #28
0
        static void Main(string[] args)
        {
            string line = "";
            //State state = StateInit();
            State state = new State();

            StateInit(state);
            State               maxValues      = MaxValuesInit();
            List <Test>         tests          = TestsInit();
            int                 iterations     = 100;
            int                 populationSize = 10;
            double              crossoverProb  = 0.1;
            double              mutationProb   = 0.1;
            double              averageFitness = 0;
            CryptoRandom        r          = new CryptoRandom();
            List <DecisionTree> population = new List <DecisionTree>();
            DecisionTree        enemy      = new DecisionTree(new List <int> {
                100, 100, 50, 0
            }, state, maxValues, tests, r);

            //DecisionTree enemy = CreateEnemy(r, state, tests);

            //population init
            for (int i = 0; i < populationSize; i++)
            {
                population.Add(new DecisionTree(new List <int> {
                    100, 100, 50, 0
                }, state, maxValues, tests, r));
                //Console.WriteLine("Wielkosc drzewa: {0}", population[i].elementCount);
                //Console.WriteLine("Wielkosc drzewa': {0}", population[i].CountElements());
            }

            while (iterations > 0)             //glowna petla programu, ustalona ilosc iteracji, pozniej dodac zatrzymanie po stagnacji
            {
                for (int j = 0; j < populationSize; j++)
                {
                    //petla walki
                    int turn = 1;
                    while (turn <= 99 && state["HP"] > 0 && state["enemyHP"] > 0)
                    {
                        //Console.WriteLine("Osobnik {0}, tura: {1}", j, turn);
                        //EnemyMakeMove(enemy.decide(state), state);
                        EnemyMoves(state);
                        MakeMove(population[j].decide(state), state);
                        turn++;
                    }
                    //Console.WriteLine("HP -> {0}", state["HP"]);
                    //Console.WriteLine("enemyHP -> {0}", state["enemyHP"]);
                    //Console.WriteLine("distance -> {0}", state["distance"]);
                    //Console.WriteLine("isInDanger -> {0}", state["isInDanger"]);
                    //Console.WriteLine("enemyIsInDanger -> {0}", state["enemyIsInDanger"]);
                    //Console.WriteLine("isDefending -> {0}", state["isDefending"]);
                    //Console.WriteLine("enemyIsDefending -> {0}", state["enemyIsDefending"]);
                    //Console.ReadLine();

                    population[j].fitness = Evaluate(state, maxValues, turn, population[j].elementCount);

                    //state = StateInit();
                    StateInit(state);
                }

                averageFitness = population.Sum(p => p.fitness) / populationSize;
                Console.WriteLine("srednia wartosc funkcji oceny: " + averageFitness);
                Console.WriteLine("najgorszy osobnik: " + population.Min(p => p.fitness));
                Console.WriteLine("najlepszy osobnik: " + population.Max(p => p.fitness));
                line = String.Concat(line, (averageFitness.ToString() + " " + population.Max(p => p.fitness) + " " + "\r\n"));

                //selekcja
                List <DecisionTree> SelectedIndividuals = EliteRankingSelection(population, populationSize, r);

                //wybranie najlepszego z poprzedniej populacji i ustawienie na enemy
                //enemy = population.OrderByDescending(p => p.fitness).First().Clone();

                population.Clear();                 // usuniecie starej populacji

                //wybranie osobnikow do krzyzowania, przepisanie reszty do nowej populacji
                List <DecisionTree> IndividualsToCross = new List <DecisionTree>();
                for (int i = 0; i < populationSize; i++)
                {
                    if (r.NextDouble() <= crossoverProb)
                    {
                        IndividualsToCross.Add(SelectedIndividuals[i]);
                    }
                    else
                    {
                        population.Add(SelectedIndividuals[i]);
                    }
                }
                //zapewnienie parzystej ilosci osobnikow do krzyzowania
                if (IndividualsToCross.Count % 2 != 0)
                {
                    population.Add(IndividualsToCross.Last());
                    IndividualsToCross.RemoveAt(IndividualsToCross.Count - 1);
                }

                Console.WriteLine("Skrzyzowane osobniki: " + IndividualsToCross.Count);
                //krzyzowanie
                while (IndividualsToCross.Count > 0)
                {
                    DecisionTree Individual1 = IndividualsToCross[r.Next(0, IndividualsToCross.Count)];
                    IndividualsToCross.Remove(Individual1);
                    DecisionTree Individual2 = IndividualsToCross[r.Next(0, IndividualsToCross.Count)];
                    IndividualsToCross.Remove(Individual2);
                    Crossover(Individual1, Individual2, r);
                    population.Add(Individual1);
                    population.Add(Individual2);
                }

                int mutationCount = 0;
                //mutacja
                for (int i = 0; i < populationSize; i++)
                {
                    if (r.NextDouble() <= mutationProb)
                    {
                        Mutation(population[i], r, state, maxValues, tests);
                        mutationCount++;
                    }
                }
                Console.WriteLine("Zmutowane osobniki: " + mutationCount);

                iterations--;
                Console.ReadLine();
            }
            System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\test.txt");
            file.WriteLine(line);

            file.Close();
            Console.ReadLine();
        }
Пример #29
0
        public static IEnumerable <T> ShuffleLinq <T>(this IEnumerable <T> enumerable)
        {
            var rand = new CryptoRandom();

            return(enumerable.OrderBy(x => rand.NextDouble()));
        }
Пример #30
0
        /// <summary>
        /// Expand the SimpleDatum according to the bbox.
        /// </summary>
        /// <param name="d">Specifies the SimpleDatum to expand.</param>
        /// <param name="expand_bbox">Specifies the bounding box.</param>
        /// <param name="fExpandRatio">Specifies the expansion ratio.</param>
        /// <returns>The expanded SimpleDatum is returned.</returns>
        public SimpleDatum ExpandImage(SimpleDatum d, NormalizedBBox expand_bbox, float fExpandRatio)
        {
            int nDatumChannels = d.Channels;
            int nDatumHeight   = d.Height;
            int nDatumWidth    = d.Width;

            // Get the bbox dimension.
            int   width  = (int)(nDatumHeight * fExpandRatio);
            int   height = (int)(nDatumWidth * fExpandRatio);
            float h_off  = (float)m_random.NextDouble();
            float w_off  = (float)m_random.NextDouble();

            h_off = (float)Math.Floor(h_off);
            w_off = (float)Math.Floor(w_off);

            expand_bbox.xmin = -w_off / nDatumWidth;
            expand_bbox.ymin = -h_off / nDatumHeight;
            expand_bbox.xmax = (width - w_off) / nDatumWidth;
            expand_bbox.ymax = (height - h_off) / nDatumHeight;

            // Crop the image using bbox.
            SimpleDatum expand_datum     = new SimpleDatum(d, height, width);
            int         nExpandDatumSize = nDatumChannels * height * width;

            if (d.IsRealData)
            {
                double[] rgData = new double[nExpandDatumSize];

                for (int h = (int)h_off; h < (int)h_off + nDatumHeight; h++)
                {
                    for (int w = (int)w_off; w < (int)w_off + nDatumWidth; w++)
                    {
                        for (int c = 0; c < nDatumChannels; c++)
                        {
                            int nDatumIdx  = (int)((c * nDatumHeight + h - h_off) * nDatumWidth + w - w_off);
                            int nExpandIdx = (c * height + h) * width + w;
                            rgData[nExpandIdx] = d.RealData[nDatumIdx];
                        }
                    }
                }

                expand_datum.SetData(rgData.ToList(), d.Label);
            }
            else
            {
                byte[] rgData = new byte[nExpandDatumSize];

                for (int h = (int)h_off; h < (int)h_off + nDatumHeight; h++)
                {
                    for (int w = (int)w_off; w < (int)w_off + nDatumWidth; w++)
                    {
                        for (int c = 0; c < nDatumChannels; c++)
                        {
                            int nDatumIdx  = (int)((c * nDatumHeight + h - h_off) * nDatumWidth + w - w_off);
                            int nExpandIdx = (c * height + h) * width + w;
                            rgData[nExpandIdx] = d.ByteData[nDatumIdx];
                        }
                    }
                }

                expand_datum.SetData(rgData.ToList(), d.Label);
            }

            return(expand_datum);
        }
		public void CryptoRandom_NextDouble()
		{
			Func<decimal, int, decimal> bucketFn = (val, _bucketCount) =>
			{
				if (val < 0M) return decimal.MinValue / 4;
				if (val >= 1M) return decimal.MaxValue / 2;

				decimal step = 1M / _bucketCount, m = step;
				for (int i = 0; i < _bucketCount - 1; ++i, m += step)
				{
					if (val < m) return m;
				}
				return m;
			};

			var rng = new CryptoRandom();
			Func<decimal> decimalFn = () => (decimal)rng.NextDouble();

			const int bucketCount = 200;

			const int extra_count1 = 0;
			const int extra_count2 = 0;
			const int count = 40000 * 1;
			const int totalCount = count + extra_count1 + extra_count2;

			var q1 = Enumerable.Range(0, count).Select(i => decimalFn())
				.Concat(Enumerable.Repeat(0.1M, extra_count1))
				.Concat(Enumerable.Repeat(0.9M, extra_count2)).ToList();

			var q2 = q1.AsParallel().GroupBy(val => bucketFn(val, bucketCount));
			var q3 = q2.Select(d => new { Key = d.Key, Count = d.LongCount() });

			decimal expectedMaxAverageDelta = (1M / ((decimal)Math.Pow(totalCount, 1d / 2.5)));

			decimal actualAverage = q1.Average();
			decimal actualAverageDelta = Math.Abs(actualAverage - 0.5M);
			Assert.IsTrue(actualAverageDelta < expectedMaxAverageDelta, $"Unexpected average delta: {actualAverageDelta} {expectedMaxAverageDelta}");

			decimal keySum = decimal.Round(q3.Sum(i => i.Key), 2);
			Assert.IsTrue(keySum > 0);
			Assert.IsTrue(keySum < bucketCount);

			var expectedKeySum = decimal.Round((1M + bucketCount) / 2, 2);
			Assert.IsTrue(keySum == expectedKeySum, $"Unexpected bucket key sum: {keySum} expected: {expectedKeySum}");

			var avg = q3.Select(i => i.Count).Average();
			var sumOfSquares = (from i in q3 let delta = (i.Count - avg) select delta * delta).Sum();
			var stddev = Math.Sqrt(sumOfSquares / q3.Count());

			var q4 = q3.Select(i => Math.Abs(i.Count - avg));

			decimal stddevTest1 = 0M, stddevTest2 = 0M, stddevTest3 = 0M;
			foreach (var val in q4)
			{
				if (val < stddev * 1) ++stddevTest1;
				if (val < stddev * 2) ++stddevTest2;
				if (val < stddev * 3) ++stddevTest3;
			}

			stddevTest1 = decimal.Round(stddevTest1 / bucketCount, 2);
			stddevTest2 = decimal.Round(stddevTest2 / bucketCount, 2);
			stddevTest3 = decimal.Round(stddevTest3 / bucketCount, 2);

			Assert.IsTrue(Math.Abs(stddevTest1 - 0.68M) <= 0.06M, $"{nameof(stddevTest1)} failed: {stddevTest1}"); // target: 0.68
			Assert.IsTrue(Math.Abs(stddevTest2 - 0.95M) <= 0.04M, $"{nameof(stddevTest2)} failed: {stddevTest2}"); // target: 0.95
			Assert.IsTrue(Math.Abs(stddevTest3 - 0.99M) <= 0.04M, $"{nameof(stddevTest3)} failed: {stddevTest3}"); // target: 0.99
		}
Пример #32
0
        public Armor GenerateArmor(int itemLevel, ItemClass itemClass, ItemType itemType, EqType eqType)
        {
            Armor result = null;

            if (itemClass == ItemClass.Ranged && eqType == EqType.Shield)
            {
                return(result);
            }

            ItemIcon     itemIcon  = this.GenerateItemIcon(itemClass, itemType, eqType);
            string       itemName  = this.GenerateItemName(itemClass, eqType);
            int          goldValue = this.GenerateItemGoldValue(itemLevel);
            double       itemWeight;
            ItemFeatures itemFeatures = new ItemFeatures();

            itemFeatures.EnableFeatures(ItemFeaturesType.IsDeleteAble, ItemFeaturesType.IsEquipAble,
                                        ItemFeaturesType.IsInfoAble, ItemFeaturesType.IsRepairAble, ItemFeaturesType.IsSellAble,
                                        ItemFeaturesType.IsUpgradeAble);

            if (itemType == ItemType.Armor)
            {
                itemWeight = Math.Round(CryptoRandom.NextDouble(0, 5), 2, MidpointRounding.AwayFromZero);

                Armor armor = null;

                switch (itemClass)
                {
                case ItemClass.Magic:
                {
                    armor = new Armor(itemClass, itemType, ItemSubType.None, itemIcon, eqType, itemFeatures,
                                      itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                    break;
                }

                case ItemClass.Melle:
                {
                    armor = new Armor(itemClass, itemType, ItemSubType.None, itemIcon, eqType, itemFeatures,
                                      itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease));
                    break;
                }

                case ItemClass.Ranged:
                {
                    armor = new Armor(itemClass, itemType, ItemSubType.None, itemIcon, eqType, itemFeatures,
                                      itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                      StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                    break;
                }
                }

                result = armor;
            }
            else if (itemType == ItemType.Trinket)
            {
                itemWeight = Math.Round(CryptoRandom.NextDouble(0, 2), 2, MidpointRounding.AwayFromZero);

                Armor trinket = null;

                switch (itemClass)
                {
                case ItemClass.Magic:
                {
                    trinket = new Armor(itemClass, itemType, ItemSubType.None, itemIcon, eqType, itemFeatures,
                                        itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                    break;
                }

                case ItemClass.Melle:
                {
                    trinket = new Armor(itemClass, itemType, ItemSubType.None, itemIcon, eqType, itemFeatures,
                                        itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                    break;
                }

                case ItemClass.Ranged:
                {
                    trinket = new Armor(itemClass, itemType, ItemSubType.None, itemIcon, eqType, itemFeatures,
                                        itemName, string.Empty, goldValue, itemWeight, false, false, 100, itemLevel, 0,
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Increase),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Normal),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.Decrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaIncrease),
                                        StatisticsGenerator.GenerateItemStatistics(itemLevel, ItemIndexManagement.GetRarityFromIndex(itemIcon.Rarity), StatisticsGeneratorBoostType.MegaDecrease));
                    break;
                }
                }

                result = trinket;
            }

            return(result);
        }