Esempio n. 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="n"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static MultiDirectedGraph <int, int> ErdosRenyi(int n, double p)
        {
            // Create empty graph and label provider
            var graph = new MultiDirectedGraph <int, int>();

            graph.Name = "Synthetic_ErdosRenyi_" + n + "_" + p;

            // Add n nodes
            for (int i = 0; i < n; i++)
            {
                graph.AddNode(i, 0);
            }

            // Add edges with probability p
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (StaticRandom.NextDouble() <= p)
                    {
                        graph.AddEdge(i, j, 0);
                    }
                }
            }

            return(graph);
        }
Esempio n. 2
0
        /// <summary>
        /// Sample using a random walk with teleport technique.
        /// </summary>
        /// <typeparam name="TNode"></typeparam>
        /// <typeparam name="TLabel"></typeparam>
        /// <param name="graph"></param>
        /// <param name="n">Upper bound on the number of nodes to sample.</param>
        /// <param name="p">Probability to teleport to a random node after visiting a node.</param>
        /// <returns></returns>
        public static HashSet <TNode> RandomWalkTeleport <TNode, TLabel>(this MultiDirectedGraph <TNode, TLabel> graph, int n, double p)
        {
            var V     = new HashSet <TNode>();
            var nodes = graph.Nodes.ToArray();

            n = Math.Min(n, graph.NumNodes);

            // Initial teleport
            var v = nodes[StaticRandom.Next(nodes.Length)];

            while (n > 0)
            {
                if (!V.Contains(v))
                {
                    V.Add(v);
                    n -= 1;
                }

                double t            = StaticRandom.NextDouble();
                var    outNeighbors = graph.Out(v).Select(eo => graph.Target(eo)).ToArray();

                if (t < p || outNeighbors.Length <= 0)
                {
                    // Teleport
                    v = nodes[StaticRandom.Next(nodes.Length)];
                }
                else
                {
                    v = outNeighbors[StaticRandom.Next(outNeighbors.Length)];
                }
            }

            return(V);
        }
Esempio n. 3
0
            public Term new_term(int indexVar)
            {
                double a = dots.Select(x => PointYDifference(x) * x.InputAttributeValue[indexVar]).ToList().Sum(),
                       b = dots.Select(x => PointYDifference(x)).ToList().Sum();
                double pick = a / b, left, right;

                if (sides[indexVar].one_term)
                {
                    left  = sides[indexVar].left.Parametrs[0];
                    right = sides[indexVar].left.Parametrs[2];
                }
                else
                {
                    left  = sides[indexVar].left.Pick;
                    right = sides[indexVar].right.Pick;
                }
                var test = variable_spaces[indexVar].terms.Select(x => x.Pick);

                if (pick > approx.LearnSamplesSet.InputAttributes[indexVar].Max ||
                    pick < approx.LearnSamplesSet.InputAttributes[indexVar].Min ||
                    (variable_spaces[indexVar].terms.Select(x => x.Parametrs[1]).Contains(pick)))
                {
                    pick = StaticRandom.NextDouble(left, right);
                }
                double[] parameters = new double[3] {
                    left, pick, right
                };
                Term result = new Term(parameters, sides[indexVar].left.TermFuncType, indexVar);

                return(result);
            }
Esempio n. 4
0
        public override CoolQRouteMessage OnMessageReceived(CoolQScopeEventArgs scope)
        {
            var routeMsg = scope.RouteMessage;

            if (routeMsg.MessageType == MessageType.Private)
            {
                return(null);
            }

            string[] ids = CoolQCode.GetAt(routeMsg.RawMessage);
            if (ids == null || !ids.Contains(routeMsg.ReportMeta.SelfId))
            {
                return(null);
            }
            if (StaticRandom.NextDouble() < 0.9)
            {
                return(routeMsg
                       .ToSource("", true)
                       .RandomDelaySeconds(5));
            }
            else
            {
                var cqImg = new FileImage(Path.Combine(PandaDir, "at.jpg"));
                return(routeMsg.ToSource(cqImg.ToString()));
            }
        }
Esempio n. 5
0
        public override CoolQRouteMessage OnMessageReceived(CoolQScopeEventArgs scope)
        {
            var routeMsg = scope.RouteMessage;

            if (routeMsg.MessageType == MessageType.Private)
            {
                return(null);
            }
            string groupId = routeMsg.GroupId ?? routeMsg.DiscussId;

            if (!GroupDic.ContainsKey(groupId))
            {
                GroupDic.GetOrAdd(groupId, new GroupSettings
                {
                    GroupId = groupId,
                });

                GroupDic[groupId].Task = Task.Run(DecreaseQueue);
                //GroupDic[groupId].Thread.Start();
            }

            if (GroupDic[groupId].IntQueue >= MaxNum && !GroupDic[groupId].Locked)
            {
                GroupDic[groupId].Locked = true;
                Logger.Debug(groupId + " locked");
                Logger.Success(groupId + "的" + routeMsg.UserId + "触发了复读");
                Thread.Sleep(StaticRandom.Next(1000, 8000));
                return(routeMsg.ToSource(routeMsg.RawMessage));
            }

            GroupDic[groupId].IntQueue++;
            //Logger.Debug(groupId + " incresed to " + GroupDic[groupId].IntQueue);
            return(null);

            Task DecreaseQueue()
            {
                while (true)
                {
                    Thread.Sleep(StaticRandom.Next(1000, 10000));
                    if (GroupDic[groupId].IntQueue <= 0)
                    {
                        if (GroupDic[groupId].Locked)
                        {
                            GroupDic[groupId].Locked = false;
                            Logger.Debug(groupId + " unlocked");
                        }

                        continue;
                    }

                    if (StaticRandom.NextDouble() < 0.02)
                    {
                        Thread.Sleep(StaticRandom.Next(30000, 45000));
                    }

                    GroupDic[groupId].IntQueue--;
                    //Logger.Debug(groupId + " decresed to " + GroupDic[groupId].IntQueue);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// This is a recursive method that adds a line to the point passed in, and has a chance of branching
        /// </summary>
        private static void GetLineBranch(List <Point3D[]> resultPoints, Point3D fromPoint, double radius, double maxDistFromPoint, double splitProbability, int remaining)
        {
            if (remaining < 0)
            {
                return;
            }

            int numBranches = 1;

            // See if this should do a split
            if (StaticRandom.NextDouble() < splitProbability)
            {
                numBranches = StaticRandom.NextDouble() > .8 ? 3 : 2;
            }

            for (int cntr = 0; cntr < numBranches; cntr++)
            {
                // Add a line
                Vector3D toPoint;
                do
                {
                    toPoint = (fromPoint + Math3D.GetRandomVector_Spherical(maxDistFromPoint)).ToVector();
                } while (toPoint.LengthSquared > radius * radius);

                resultPoints.Add(new Point3D[] { fromPoint, toPoint.ToPoint() });

                double newMaxDist = maxDistFromPoint * .85d;

                // Make the next call have a higher chance of branching
                double newSplitProbability = 1d - ((1d - splitProbability) / 1.2d);

                // Recurse
                GetLineBranch(resultPoints, toPoint.ToPoint(), radius, newMaxDist, newSplitProbability, remaining - 1);
            }
        }
Esempio n. 7
0
        public MainWindow()
        {
            InitializeComponent();
            List <Draw.Trunk> list = new List <Draw.Trunk>();

            for (int i = 0; i < 8; i++)
            {
                double thickness = StaticRandom.NextDouble(5, 20);
                double height    = thickness * StaticRandom.NextDouble(3.5, 4.5);
                list.Add(new Draw.Trunk(i * 150 + 50, StaticRandom.Next(200, 600),
                                        thickness, height));
            }
            //Draw.Trunk tree = new Draw.Trunk(500, 600, 18, 80);
            foreach (var tree in list)
            {
                foreach (var item in tree.ListTrunk1)
                {
                    canvas1.Children.Add(item);
                }
                Path p = new Path();
                p.Data = tree.StartOfTrees1.Tree;
                p.Fill = Brushes.Black;
                canvas1.Children.Add(p);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// This creates random size in random location
        /// TODO: Look at existing sizes more carefully to see what size to create
        /// TODO: Don't create something near the player - take a list of spheres to avoid (or maybe cubes)
        /// TODO: Have certain features of the map be sources - maybe a couple hidden moving sources that slowly move around the edge of the map
        /// TODO: When creating asteroids, create a small stream of them
        /// </summary>
        private static ChangeInstruction[] ExamineAsteroids_Add1(int count, Boundry boundry)
        {
            ChangeInstruction[] retVal = new ChangeInstruction[count];

            for (int cntr = 0; cntr < count; cntr++)
            {
                //asteroidSize = 4 + (rand.NextDouble() * 6);       // medium
                //asteroidSize = 9 + (rand.NextDouble() * 10);      // large
                double asteroidSize = 4 + StaticRandom.NextDouble(16);

                Point3D position = Math3D.GetRandomVector(boundry.Outer_Min, boundry.Outer_Max, boundry.Inner_Min, boundry.Inner_Max).ToPoint();

                Vector3D velocity = Math3D.GetRandomVector_Circular(6d);
                Vector3D angVel   = Math3D.GetRandomVector_Spherical(1d);

                AsteroidDNA asteroid = new AsteroidDNA()
                {
                    PartType        = Asteroid.PARTTYPE,
                    Radius          = asteroidSize,
                    Position        = position, //NOTE: These are duplication and aren't used, but storing them anyway
                    Velocity        = velocity,
                    AngularVelocity = angVel,
                };

                retVal[cntr] = new ChangeInstruction(position, velocity, angVel, asteroid);
            }

            return(retVal);
        }
        public int GenerateActivitiesForContacts(IEnumerable <ContactInfo> contacts, int mediumActivitiesCount, List <TreeNode> treeNodes)
        {
            var      activities = new List <ActivityInfo>();
            DateTime created    = DateTime.Now;

            foreach (var contact in contacts)
            {
                int activitiesCount = (int)(mediumActivitiesCount * StaticRandom.NextDouble() * 2);

                for (int i = 0; i < activitiesCount; i++)
                {
                    var treeNode = treeNodes[StaticRandom.Next(treeNodes.Count)];

                    var activityInfo = new ActivityInfo
                    {
                        ActivityCreated           = created,
                        ActivityType              = "pagevisit",
                        ActivityActiveContactID   = contact.ContactID,
                        ActivityOriginalContactID = contact.ContactID,
                        ActivitySiteID            = contact.ContactSiteID,
                        ActivityTitle             = "Page visit on '" + treeNode.DocumentName + "' page",
                        ActivityItemID            = 0,
                        ActivityItemDetailID      = 0,
                        ActivityURL         = treeNode.DocumentUrlPath,
                        ActivityNodeID      = treeNode.NodeID,
                        ActivityValue       = "",
                        ActivityIPAddress   = "123.123.456.789",
                        ActivityCampaign    = "",
                        ActivityURLReferrer = treeNode.DocumentUrlPath + "-totojereferrer",
                        ActivityCulture     = treeNode.DocumentCulture,
                    };

                    activities.Add(activityInfo);
                }
            }
            BulkInsertion.Insert(activities);

            var activityIds = ActivityInfoProvider.GetActivities().WhereEquals("ActivityCreated", created).Select(a => a.ActivityID);

            var pageVisits = new List <PageVisitInfo>();

            foreach (var activityId in activityIds)
            {
                var pageVisitInfo = new PageVisitInfo
                {
                    PageVisitActivityID         = activityId,
                    PageVisitMVTCombinationName = "",
                    PageVisitABVariantName      = "",
                    PageVisitDetail             = "?totojequerystring=prase",
                };

                pageVisits.Add(pageVisitInfo);
            }

            BulkInsertion.Insert(pageVisits);

            return(activities.Count);
        }
Esempio n. 10
0
 public virtual void WJVector_gen(int j)
 {
     WJVector = new KnowlegeBaseTSARules(monkey[j]);
     for (int k = 0; k < monkey[j].TermsSet.Count; k++)
     {
         for (int q = 0; q < monkey[j].TermsSet[k].CountParams; q++)
         {
             WJVector.TermsSet[k].Parametrs[q] += 2 * (StaticRandom.NextDouble() - 0.5) * watch_jump_parameter;
         }
     }
 }
Esempio n. 11
0
        private RuleInfo GenerateMacroRule(int siteId)
        {
            var rule = GenerateBaseRule(RuleTypeEnum.Macro, siteId);

            string value = StaticRandom.NextDouble() < 0.5 ? "true" : "false";

            rule.RuleCondition   = string.Format("<condition><macro><value>{{%{0}%}}</value></macro></condition>", value);
            rule.RuleDisplayName = string.Format("Macro rule for {0} points which is always {1}", rule.RuleValue, value);

            return(rule);
        }
Esempio n. 12
0
        public static Vector3 GetRandomInUnitSphere()
        {
            Vector3 point;

            do
            {
                point = 2f * new Vector3((float)StaticRandom.NextDouble(), (float)StaticRandom.NextDouble(),
                                         (float)StaticRandom.NextDouble()) - Vector3.One;
            } while (point.LengthSquared() >= 1f);

            return(point);
        }
Esempio n. 13
0
        /// <summary>
        /// Creates and return a random rowNum-by-colNum  matrix with values between '0' and 'prime-1'.
        /// </summary>
        public static ZpMatrix GetRandomMatrix(int rowNum, int colNum, int prime)
        {
            var A = new ZpMatrix(rowNum, colNum, prime);

            for (int i = 0; i < rowNum; i++)
            {
                for (int j = 0; j < colNum; j++)
                {
                    A.data[i][j] = Zp.Modulo((int)(StaticRandom.NextDouble() * (prime)), prime);
                }
            }
            return(A);
        }
Esempio n. 14
0
        private bool ShouldParticipateInChain(MessageChainData currentChain)
        {
            var baseChance            = Double.Parse(Config.Get("MessageChainBaseChance", "0.125"));
            var multiplier            = Double.Parse(Config.Get("MessageChainChanceMultiplier", "2"));
            var chanceOfParticipating = 0.0;

            if (currentChain.Length > 1)
            {
                chanceOfParticipating = baseChance * Math.Pow(multiplier, currentChain.Length - 2);
            }

            return(StaticRandom.NextDouble() < chanceOfParticipating);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates or adds to a set of colors to be used by klinth weapons
        /// </summary>
        /// <param name="existing">This is a material definition that may already exist, or partially filled out</param>
        /// <param name="basedOn">This is a way to force the return hue (a spike ball's colors could be based on the handle's colors)</param>
        public static MaterialDefinition[] GetRandomMaterials_Klinth(MaterialDefinition[] existing = null, ColorHSV?basedOn = null)
        {
            List <MaterialDefinition> retVal = new List <MaterialDefinition>();

            Random rand = StaticRandom.GetRandomForThread();

            if (existing != null)
            {
                retVal.AddRange(existing);
            }

            // Main color (in the case of a handle, the only color)
            if (retVal.Count < 1)
            {
                double hue;
                if (basedOn == null)
                {
                    hue = StaticRandom.NextDouble(0, 360);
                }
                else
                {
                    //hue = GetRandomHue(basedOn.Value.H);
                    hue = basedOn.Value.H;      // klinth shouldn't allow an opposite hue (it looks really bad)
                }

                retVal.Add(new MaterialDefinition()
                {
                    DiffuseColor  = UtilityWPF.HSVtoRGB(hue, StaticRandom.NextDouble(50, 80), StaticRandom.NextDouble(40, 90)).ToHex(),
                    SpecularColor = UtilityWPF.HSVtoRGB(StaticRandom.NextDouble(0, 360), StaticRandom.NextDouble(50, 80), StaticRandom.NextDouble(40, 90)).ToHex(),
                    EmissiveColor = UtilityWPF.GetRandomColor(0, 255).ToHex()
                });
            }

            // Secondary color (in the case of ball and spikes, this is the spikes)
            if (retVal.Count < 2)
            {
                ColorHSV firstDiff = UtilityWPF.ColorFromHex(retVal[0].DiffuseColor).ToHSV();
                ColorHSV firstSpec = UtilityWPF.ColorFromHex(retVal[0].SpecularColor).ToHSV();
                ColorHSV firstEmis = UtilityWPF.ColorFromHex(retVal[0].EmissiveColor).ToHSV();

                // Needs to be roughly the same color as the ball, just a bit darker
                retVal.Add(new MaterialDefinition()
                {
                    DiffuseColor  = UtilityWPF.HSVtoRGB(firstDiff.H, firstDiff.S * 1.25, firstDiff.V * .66d).ToHex(),
                    SpecularColor = UtilityWPF.HSVtoRGB(firstSpec.H, firstSpec.S * 1.1, firstSpec.V).ToHex(),
                    EmissiveColor = UtilityWPF.HSVtoRGB(firstEmis.H, firstEmis.S, firstEmis.V).ToHex(),
                });
            }

            return(retVal.ToArray());
        }
Esempio n. 16
0
        /// <summary>
        /// This should get called on an infrequent basis, and randomize the available inventory
        /// </summary>
        public void RandomizeInventory(bool completelyNew)
        {
            RandomizePrices();

            if (completelyNew)
            {
                this.StationInventory.Clear();
            }

            List <Inventory> inventory = new List <Inventory>();

            // Ships
            inventory.AddRange(AdjustInventory(
                                   this.StationInventory.Where(o => o.Ship != null),
                                   3,
                                   () =>
            {
                DefaultShipType shipType = GetRandomItemChance(_shipChances).ShipType;
                ShipDNA shipDNA          = DefaultShips.GetDNA(shipType);
                return(new Inventory(shipDNA, StaticRandom.NextDouble(.5, 2)));
            }));


            // Parts
            inventory.AddRange(AdjustInventory(
                                   this.StationInventory.Where(o => o.Part != null),
                                   4,
                                   () =>
            {
                PartCreateChance partType = GetRandomItemChance(_partChances);
                ShipPartDNA partDNA       = GetRandomPart(partType);    //TODO: Have a chance to make 2 if it's something that could come in pairs (thruster, gun, etc)
                return(new Inventory(partDNA));
            }));

            // Minerals
            inventory.AddRange(AdjustInventory(
                                   this.StationInventory.Where(o => o.Mineral != null),
                                   4,
                                   () =>
            {
                MineralType type = UtilityCore.GetRandomEnum <MineralType>();
                double volume    = StaticRandom.NextPercent(ItemOptionsAstMin2D.MINERAL_AVGVOLUME, 2);
                return(new Inventory(ItemOptionsAstMin2D.GetMineral(type, volume)));
            }));

            this.StationInventory.Clear();
            this.StationInventory.AddRange(inventory);

            _inventoryRandomizeCountdown = StaticRandom.NextDouble(3 * 60, 8 * 60);
        }
Esempio n. 17
0
        private static bool Trig(string message, IEnumerable <string> keywords, IReadOnlyList <string> pics,
                                 out string imgP, double chancePercent = 10)
        {
            var    chance = chancePercent / 100d;
            string msg    = message.ToLower();

            if (keywords.Any(msg.Contains))
            {
                imgP = pics[StaticRandom.Next(pics.Count)];
                return(StaticRandom.NextDouble() < chance);
            }

            imgP = null;
            return(false);
        }
Esempio n. 18
0
 public void NextDoubleShouldNotAlwaysReturnInts()
 {
     // We might get a double like 1.0 *once*, but we're unlikely
     // to get 10 of them unless there's a bug (like the one
     // prompting this test)
     for (int i = 0; i < 10; i++)
     {
         double d = StaticRandom.NextDouble();
         if ((int)d != d)
         {
             return;
         }
     }
     Assert.Fail("NextDouble shouldn't just return ints");
 }
Esempio n. 19
0
        /// <summary>
        /// 核心识别by sahuang
        /// </summary>
        private static void RunDetector(object groupSets)
        {
            var gSets = (GroupSettings)groupSets;

            while (gSets.PathQueue.Count != 0)
            {
                try
                {
                    CreateProc(gSets);
                    ProcExited(gSets);
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
                finally
                {
#if DEBUG
                    _totalCount--;
                    Logger.Info("(熊猫) " + (_totalCount + 1) + " ---> " + _totalCount);
#endif
                }
            }

            if (gSets.PandaCount < 1)
            {
                return;
            }
#if DEBUG
            Logger.Info("[" + gSets.GroupId + "] (熊猫) " + gSets.PandaCount);
#endif
            for (int i = 0; i < gSets.PandaCount; i++)
            {
                var perc = StaticRandom.NextDouble();
                if (perc >= 0.15)
                {
                    continue;
                }
                Logger.Success("[" + gSets.GroupId + "] (熊猫) 几率: " + perc);

                string     resPath = Path.Combine(Domain.PluginPath, "dragon", "resource_panda_send");
                FileInfo[] files   = new DirectoryInfo(resPath).GetFiles();
                var        cqImg   = new FileImage(files[StaticRandom.Next(files.Length)].FullName).ToString();
                SendMessage(gSets.routeMsg.ToSource(cqImg));
            }

            gSets.Clear();
        }
Esempio n. 20
0
        /// <summary>
        /// This returns a value that is reasonable for the length of the handle
        /// </summary>
        public static double GetRandomRadius(double handleRadius, double handleLength)
        {
            //const double AVGLENGTH = 2.1;

            double min = handleRadius * 2d;
            double max = handleRadius * 2.6d;

            //// Adjust min/max based on the length of the handle (assuming
            ////TODO: Don't be so linear
            //double distPercent = (handleLength) / AVGLENGTH;

            //min *= distPercent;
            //max *= distPercent;

            return(StaticRandom.NextDouble(min, max));
        }
Esempio n. 21
0
 public static double[] ClimbVectorR(int length, double step)
 {
     double[] V = new double[length];
     for (int i = 0; i < length; i++)
     {
         if (StaticRandom.Next(2) == 0)
         {
             V[i] = 2 * step * StaticRandom.NextDouble();
         }
         else
         {
             V[i] = 2 * (-step) * StaticRandom.NextDouble();
         }
     }
     return(V);
 }
Esempio n. 22
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!_isInitialized)
                {
                    return;
                }

                bool shouldSwitch = false;
                if ((DateTime.UtcNow - _lastRotateSwitch).TotalSeconds > 10)
                {
                    shouldSwitch      = true;
                    _lastRotateSwitch = DateTime.UtcNow;
                }

                foreach (VisualTracker tracker in _visuals)
                {
                    if (shouldSwitch)
                    {
                        // Set a new random angle
                        tracker.Transform.Axis = Math3D.GetRandomVector_Spherical(1);
                        tracker.DeltaAngle     = StaticRandom.NextDouble(-DELTAANGLE, DELTAANGLE);
                    }

                    // Rotate it
                    double angle = tracker.Transform.Angle;

                    angle += tracker.DeltaAngle;

                    if (angle > 360)
                    {
                        angle -= 360;
                    }
                    else if (angle < 0)
                    {
                        angle += 360;
                    }

                    tracker.Transform.Angle = angle;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public static T GetWeightedRandomKey <T>(this Dictionary <T, double> weightedKeys)
        {
            double totalWeights   = weightedKeys.Values.Sum();
            double selectedWeight = StaticRandom.NextDouble() * totalWeights;
            T      source         = weightedKeys.Keys.FirstOrDefault();

            foreach ((T tempSource, double tempWeight) in weightedKeys)
            {
                source          = tempSource;
                selectedWeight -= tempWeight;
                if (selectedWeight <= 0)
                {
                    break;
                }
            }
            return(source);
        }
Esempio n. 24
0
        private static Operations GetWeightedOperation(int step, Dictionary <Operations, Func <int, double> > weightProviders, List <Operations> skipOperations)
        {
            List <(Operations, double)> weights = weightProviders.Where(kvp => !skipOperations.Contains(kvp.Key)).Select(kvp => (kvp.Key, kvp.Value(step))).ToList();
            double totalWeight    = weights.Sum(kvp => kvp.Item2);
            double selectedWeight = StaticRandom.NextDouble() * totalWeight;

            foreach ((Operations operation, double weight) in weights)
            {
                selectedWeight -= weight;
                if (selectedWeight <= 0.0)
                {
                    return(operation);
                }
            }

            //Failsafe.
            return(Operations.Swap);
        }
Esempio n. 25
0
        private void CreateFields()
        {
            _gravityField = new GravityFieldSpace(_map);

            // These two can't deviate too far from each other.  Too much gravity with no swirl will just make a big blob.  Too much swirl with no gravity
            // isn't as bad, but more gravity makes it more interesting
            double gravitationalConstant = UtilityCore.GetScaledValue(.0001d, .0005d, 0d, 1d, StaticRandom.NextDouble());
            double swirlStrength         = UtilityCore.GetScaledValue(50d, 600d, 0d, 1d, StaticRandom.NextDouble());

            double percent = UtilityCore.GetScaledValue(.1d, 1.5d, 0d, 1d, StaticRandom.NextDouble());

            gravitationalConstant *= percent;
            swirlStrength         *= percent;

            _gravityField.GravitationalConstant = gravitationalConstant;

            _gravityField.Swirl   = new GravityFieldSpace.SwirlField(swirlStrength, new Vector3D(0, 0, 1), 10d);
            _gravityField.Boundry = new GravityFieldSpace.BoundryField(.85d, 5000d, 2d, _boundryMin, _boundryMax);
        }
Esempio n. 26
0
        static string Child(string first, string second)
        {
            StringBuilder child = new StringBuilder();

            for (int i = 0; i < first.Length; i++)
            {
                if (StaticRandom.NextDouble() < range)
                {
                    child.Append(RandChar(Math.Min((int)first[i], (int)second[i]) - 30,
                                          Math.Max((int)first[i], (int)second[i]) + 30));
                }
                else
                {
                    child.Append((first[i].ToString() +
                                  second[i].ToString())[StaticRandom.Next(0, 2)]);
                }
            }
            return(child.ToString());
        }
Esempio n. 27
0
            public static double NextGaussian(double mu = 0, double sigma = 1)
            {
                double x, u, v, s;

                if (isStored)
                {
                    isStored = !isStored;
                    return(prevGauss * sigma + mu);
                }
                do
                {
                    u = 2 * StaticRandom.NextDouble() - 1;
                    v = 2 * StaticRandom.NextDouble() - 1;
                    s = u * u + v * v;
                } while (s >= 1 || s == 0);
                x         = Math.Sqrt(-2 * Math.Log(s) / s);
                prevGauss = x * u;
                isStored  = !isStored;
                return(x * v * sigma + mu);
            }
Esempio n. 28
0
        private RuleInfo GenerateRule(int siteId)
        {
            var          random   = StaticRandom.NextDouble();
            RuleTypeEnum ruleType = random < 0.166 ?
                                    RuleTypeEnum.Attribute : random < 0.333 ?
                                    RuleTypeEnum.Macro : RuleTypeEnum.Activity;

            switch (ruleType)
            {
            case RuleTypeEnum.Activity:
                return(GenerateActivityRule(siteId));

            case RuleTypeEnum.Attribute:
                return(GenerateAttributeRule(siteId));

            case RuleTypeEnum.Macro:
                return(GenerateMacroRule(siteId));
            }

            return(null);
        }
Esempio n. 29
0
        private void Broadcast(NetworkContextImpl senderContext, byte[] buffer, int offset, int length)
        {
            byte[] payload = new byte[length];
            Buffer.BlockCopy(buffer, offset, payload, 0, length);

            if (StaticRandom.NextDouble() > Math.Sqrt(1 - dropRate))
            {
                return;
            }
            foreach (var context in contexts)
            {
                if (StaticRandom.NextDouble() > Math.Sqrt(1 - dropRate))
                {
                    return;
                }
                if (context != senderContext)
                {
                    context.HandleDataArrived(payload);
                }
            }
        }
Esempio n. 30
0
        private static T GetRandomItemChance <T>(T[] items) where T : IItemChance
        {
            double randValue = StaticRandom.NextDouble();

            double sum = 0;

            foreach (T item in items)
            {
                sum += item.ProbabilityPercent;

                if (sum > randValue)
                {
                    return(item);
                }
            }

            if (sum.IsNearValue(1))
            {
                return(items[items.Length - 1]);
            }

            throw new ApplicationException("Couldn't pick a random item.  The percents don't add to one: " + sum.ToString());
        }