private static void ReadNames() { names = new WeightedRandom<string>(); XDocument doc = XDocument.Load("donations.xml"); foreach(XElement element in doc.Descendants("Donation")) { string name = element.Element("Name").Value; int weight = Int32.Parse(element.Element("Amount").Value); names.AddValue(weight, name); } }
public override string GetChat() { WeightedRandom <string> chats = new WeightedRandom <string>(); const int count = 9; for (int i = 1; i < count + 1; i++) { chats.Add(Language.GetTextValue("Mods.PboneUtils.TownChat.MysteriousTrader." + i)); } return(chats.Get()); }
protected override void FillLootBox(WeightedRandom <LootBoxContents> WR) { WR.Add(new LootBoxContents(ItemID.InfernoPotion, 1 + Main.rand.Next(Main.rand.Next(2, 15))), 1); WR.Add(new LootBoxContents(ItemID.ObsidianSkinPotion, 1 + Main.rand.Next(Main.rand.Next(2, 15))), 1); WR.Add(new LootBoxContents(ItemID.LifeforcePotion, 1 + Main.rand.Next(Main.rand.Next(2, 15))), 1); WR.Add(new LootBoxContents(ItemID.EndurancePotion, 1 + Main.rand.Next(Main.rand.Next(2, 15))), 1); WR.Add(new LootBoxContents(ItemID.TeleportationPotion, 1 + Main.rand.Next(Main.rand.Next(2, 15))), 1); WR.Add(new LootBoxContents(ItemID.GravitationPotion, 1 + Main.rand.Next(Main.rand.Next(2, 15))), 1); WR.Add(new LootBoxContents(ItemID.SuperHealingPotion, 5 + Main.rand.Next(Main.rand.Next(5, 15))), 0.5); WR.Add(new LootBoxContents(ItemID.SuperManaPotion, 5 + Main.rand.Next(Main.rand.Next(5, 15))), 0.5); loots.Add(WR.Get()); }
public static int ChooseNewQuest() { var questChoice = new WeightedRandom <int>(); for (int i = 0; i < Quests.Count; i++) { if (Quests[i].IsAvailable()) { questChoice.Add(i, Quests[i].Weight); } } return(questChoice); }
/// <summary> /// Transforms the given string collection to a WeightedRandom /// Parses the weight given in the string in the format: string:weight /// Weight defaults to 1 /// </summary> public static WeightedRandom <string> ToWeightedCollectionWithWeight(this string[] strings) { WeightedRandom <string> weightedCollection = new WeightedRandom <string>(); for (int i = 0; i < strings.Length; i++) { string str = strings[i]; string[] split = str.Split(':'); double weight = split.Length > 1 ? Double.Parse(split[1]) : 1d; weightedCollection.Add(split[0], weight); } return(weightedCollection); }
public void WeightedRandom_Dictionary() { Dictionary <int, int> probebilities = new Dictionary <int, int>() { { 10, 1 }, { 20, 2 }, { 30, 3 }, }; _weightedRandom = new WeightedRandom(probebilities); Assert.AreEqual(probebilities, _probebilities); Assert.AreEqual(6, _totalProbability); }
/** * Convert the model into a binary-searchable model for fast lookups. * Running this will allow Transitions. */ public void Prepare() { if (validated) { throw new Exception("Model has already been prepared."); } for (int i = 0; i < STATE_COUNT; i++) { WeightedRandom.MakeWeightArraySearchable(binarySearchPModel[i]); } validated = true; }
public void WeightedRandom_Dictionary_NegativeProbability() { Dictionary <int, int> probebilities = new Dictionary <int, int>() { { 10, 1 }, { 20, 2 }, { 30, -10 }, }; _weightedRandom = new WeightedRandom(probebilities); Assert.AreEqual(2, _probebilities.Count); Assert.AreEqual(3, _totalProbability); }
public override string GetChat() { WeightedRandom <string> chat = new WeightedRandom <string>(); if (NPC.FindFirstNPC(NPCID.DyeTrader) != -1) { chat.Add(Language.GetTextValue("Mods.EvanModpack.NPCDialog.AudioEngineer0", Main.npc[NPC.FindFirstNPC(NPCID.DyeTrader)].GivenName)); } for (int i = 1; i < 7; ++i) { chat.Add(Language.GetText(string.Format("Mods.EvanModpack.NPCDialog.AudioEngineer{0}", i)).Value); } return(chat); }
public string GetDialogue(string deviName) { WeightedRandom <string> dialogueChooser = new WeightedRandom <string>(); (List <HelpDialogue> sortedDialogue, int type) = SortDialogue(deviName); foreach (HelpDialogue dialogue in sortedDialogue) { dialogueChooser.Add(dialogue.Message); } lastDialogueType = type; return(dialogueChooser); }
/*public override void FindFrame(int frameHeight) * { * npc.frameCounter += 1; * npc.frameCounter %= 20; * int frame = (int)(npc.frameCounter / 2.0); * if(frame >= Main.npcFrameCount[npc.type]) * { * frame = 0; * } * npc.frame.Y = frame * frameHeight; * }*/ public override void NPCLoot() { if (Main.expertMode) { npc.DropBossBags(); } else { if (Main.rand.NextBool(7)) { // Mask //player.QuickSpawnItem(mod.ItemType(" ")); } int[] drops = { mod.ItemType("GoldenGun"), mod.ItemType("SunPowerSeed"), mod.ItemType("BeskarBar") }; var dropChooser = new WeightedRandom <int>(); for (int i = 0; i < drops.Length; ++i) { dropChooser.Add(drops[i], 1); } int choice = dropChooser; player.QuickSpawnItem(choice); dropChooser.Clear(); for (int i = 0; i < drops.Length; ++i) { if (drops[i] != choice) { dropChooser.Add(drops[i], 1); } } int choice2 = dropChooser; player.QuickSpawnItem(choice2); player.QuickSpawnItem(ItemID.GoldCoin, Main.rand.Next(15, 20)); player.QuickSpawnItem(mod.ItemType("BeskarOre"), Main.rand.Next(15, 20)); } SpawnOre(); if (!EGGWorld.downedSunGod) { EGGWorld.downedSunGod = true; if (Main.netMode == NetmodeID.Server) { NetMessage.SendData(MessageID.WorldData); // Immediately inform clients of new world state. } } }
public override string GetChat() { WeightedRandom <string> chat = new WeightedRandom <string>(); int wizard = NPC.FindFirstNPC(NPCID.Wizard); if (wizard >= 0) { chat.Add("I'm glad to see " + Main.npc[wizard].GivenName + " back"); } chat.Add("Potions? Yes, I have some"); chat.Add("Did you know that if you mix mushrooms with blinkroot, you can see the future!"); chat.Add("You won't see potions better than mine"); return(chat); }
void Start() { dragValue = gameObject.GetComponent <Stats>().drag; gameObject.GetComponent <PirateBehaviour>().onBehaviourChanged.AddListener(HandleOnBehaviourChanged); pirate = gameObject.GetComponent <Rigidbody2D>(); topSpeed = gameObject.GetComponent <Stats>().speed; doAction = null; weapon = gameObject.GetComponent <Weapon>(); if (firePos == null) { firePos = gameObject.transform.Find("FirePosition"); } List <randomAction> attackList = new List <randomAction>(); attackList.Add(new randomAction(10, 2, Rotate)); attackList.Add(new randomAction(100, 0, Idling)); attackList.Add(new randomAction(5, 0.3f, Fire)); rand = new WeightedRandom <randomAction>(attackList); /* #region Testing Random * * WeightedRandom<Actioneer> Wr = new WeightedRandom<Actioneer>(); * Wr.AddItem(new Actioneer("first", 5)); * Wr.AddItem(new Actioneer("2nd", 1)); * Wr.AddItem(new Actioneer("3nd", 33)); * Wr.AddItem(new Actioneer("4nd", 2)); * Wr.AddItem(new Actioneer("5th", 3)); * Wr.AddItem(new Actioneer("6th", 7)); * Wr.AddItem(new Actioneer("7th", 6)); * int i = 0; * * for (int j = 0; j < 100; j++) * { * Debug.Log(" Random Weight" + Wr.GetRandomValue(out i).name); * } * * /*foreach (var items in Wr.allWeights()) * Debug.Log("Random Weight " + items.Weight + " " + items.name); * * #endregion */ }
void Start() { int size = 500; Dictionary <string, double> myDictionary = new Dictionary <string, double> { { "Sphere", 0.5 }, { "Cube", 0.1 }, { "Capsule", 0.2 }, { "Cylinder", 0.2 } }; WeightedRandom weighted = new WeightedRandom(); List <string> values = weighted.RandomList(size, myDictionary); gameObjects = new List <GameObject>(size); for (int i = 0; i < values.Count; i++) { GameObject go; if (values[i].Equals("Sphere")) { go = GameObject.CreatePrimitive(PrimitiveType.Sphere); go.GetComponent <Renderer>().material.color = Color.red; } else if (values[i].Equals("Cube")) { go = GameObject.CreatePrimitive(PrimitiveType.Cube); go.GetComponent <Renderer>().material.color = Color.blue; } else if (values[i].Equals("Capsule")) { go = GameObject.CreatePrimitive(PrimitiveType.Capsule); go.GetComponent <Renderer>().material.color = Color.cyan; } else { go = GameObject.CreatePrimitive(PrimitiveType.Cylinder); go.GetComponent <Renderer>().material.color = Color.green; } go.AddComponent <Rigidbody>(); go.SetActive(false); Instantiate(go, Vector3.zero, Quaternion.identity); gameObjects.Add(go); } StartCoroutine(InvokeMethod(SpawnGameobject, gameObjects.Count)); }
public Vector2 GetRandomFringePoint() { WeightedRandom wr = new WeightedRandom(); foreach (CircleNode node in fringe) { foreach (Slice slice in node.freeSlices) { wr.AddRange(/* TODO: slice min, slice max, slice length*/) } } float result = wr.GetFloat(); return(result); }
// TODO: Add localization support public override string TownNPCName() { WeightedRandom <string> name = new WeightedRandom <string>(); name.Add("Arne"); name.Add("Egil"); name.Add("Gunnar"); name.Add("Harald"); name.Add("Hjalmar"); name.Add("Leif"); name.Add("Ragnar"); name.Add("Nisse", 0.5); return(name.Get()); }
private Texture2D GetBubble() { WeightedRandom <Texture2D> wr = new WeightedRandom <Texture2D>(Main.rand); wr.Add(possibleBubbleTextures[0], 0.1f); wr.Add(possibleBubbleTextures[1], 0.1f); wr.Add(possibleBubbleTextures[2], 0.05f); wr.Add(possibleBubbleTextures[3], 0.05f); wr.Add(possibleBubbleTextures[4], 0.2f); wr.Add(possibleBubbleTextures[5], 0.3f); wr.Add(possibleBubbleTextures[6], 0.025f); wr.Add(possibleBubbleTextures[7], 0.175f); return(wr.Get()); }
public Trait GetRandomTrait(Trait oldTrait) { WeightedRandom <Trait> traitChooser = new WeightedRandom <Trait>(); for (int i = 0; i < byIndex.Count; i++) { if (byIndex[i] == oldTrait || byIndex[i] == Default || byIndex[i].Percentage < 0) { continue; } traitChooser.Add(byIndex[i]); } return(traitChooser); }
public override void ExtractinatorUse(ref int resultType, ref int resultStack) { var GemTypeAndStackChooser = new WeightedRandom <Tuple <int, int> >(); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Sapphire, Main.rand.Next(1, 5))); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Ruby, Main.rand.Next(1, 5))); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Emerald, Main.rand.Next(1, 5))); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Topaz, Main.rand.Next(1, 5))); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Amethyst, Main.rand.Next(1, 5))); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Diamond, Main.rand.Next(1, 5))); GemTypeAndStackChooser.Add(new Tuple <int, int>(ItemID.Amber, Main.rand.Next(1, 5))); Tuple <int, int> GemTypeAndStack = GemTypeAndStackChooser; resultType = GemTypeAndStack.Item1; resultStack = GemTypeAndStack.Item2; }
public override string GetChat() { WeightedRandom <string> chat = new WeightedRandom <string>(); int partyGirl = NPC.FindFirstNPC(NPCID.PartyGirl); if (partyGirl >= 0 && Main.rand.NextBool(4)) { chat.Add("Can you remind " + Main.npc[partyGirl].GivenName + " that she still has my shotgun?"); } chat.Add("I'm pretty sure my cows keep escaping."); chat.Add("Make it snappy. I've got work to do."); chat.Add("I've heard legend of a giant cow that's turned carnivore. Or maybe I saw it.. I can't remember"); chat.Add("Oh good, a sl... worker. Grab a shovel and start helping."); chat.Add("Where are you going with that money? Come and give me some of that!", 0.1); return(chat); }
public override WeightedRandom <string> GetDialogueText() { WeightedRandom <string> chat = new WeightedRandom <string>(); if (isHatedRep || isNegativeRep || Main.bloodMoon) { chat.Add("Don’t take it personally if we like, rip off your arms and eat you or something."); chat.Add("How do you even live with those repulsive meat sticks in place of wings?"); chat.Add("You really ruffle my feathers, landwalker!"); chat.Add("How’s the weather down there? I hope it’s horrible."); chat.Add("Leave me alone you ugly landwalking son of a- squak!"); chat.Add("Do you want my feathers going down your back like a stegosaurus?", 0.66); chat.Add("Are all the flightless this fowl and annoying...?"); chat.Add("Humans... Despicable. Created those foul windows!"); } else if (isNeutralRep) { chat.Add("I don’t get it, what’s so wrong with being bird-brained?"); chat.Add("No, I don’t want any crackers. And stop calling me Polly!", 0.66); chat.Add("I hope I can be at the front of the V formation at least once before I die."); chat.Add("Flying through the sky is like, so freeing. You should try it sometime."); chat.Add("You’re asking how we reproduce if we’re all female? Don’t be silly.", 0.33); chat.Add("I’m sort of scared of flying too high and floating into space or the sun or something."); chat.Add("You’ll buy something, won’t you? You didn’t come here for nothing, right?"); } else if (isPositiveRep || isMaxRep) { chat.Add(Main.LocalPlayer.name + "! You want to buy something, right? Or did you just want to talk to me?"); chat.Add("Aren’t my feathers pretty today? I spent all day grooming them."); chat.Add("Does this top make my wings look fat?", 0.66); chat.Add("You should sit with me on my perch sometime. The breeze is so nice, it really helps my zen."); chat.Add("You aren’t so bad for a landwalking human. Come visit again sometime!"); chat.Add("It gets sort of boring up here. But it’s not so bad when you come around."); chat.Add("ptoo- Sorry, I got a feather in my mouth again. Happens every time.", 0.66); chat.Add("No I’m not flirting with you! Stupid human!", 0.33); } //General Event Chat //Rain chat.ConditionalStringAdd("I’m super thankful we’re above the clouds. I cannot stand my hair being wet.", Main.raining, 2); chat.ConditionalStringAdd("Ahh, watching the rain fall from the clouds is so relaxing.", Main.raining, 2); //Solar Eclipse chat.ConditionalStringAdd("It’s so fun watching all the monsters going crazy down there attacking people. I’m glad we’re somewhat safe up here.", Main.eclipse, 2); chat.ConditionalStringAdd("What, are you scared or something?", Main.eclipse, 2); return(chat); }
protected override void FillLootBox(WeightedRandom <LootBoxContents> WR) { foreach (int itemtype in Dimensions.DeeperDungeon.CommonItems) { WR.Add(new LootBoxContents(itemtype, itemtype == ModContent.ItemType <Weapons.Almighty.Megido>() ? Main.rand.Next(8, 17) : 1), 1); } foreach (int itemtype in Dimensions.DeeperDungeon.RareItems) { WR.Add(new LootBoxContents(itemtype, 1), 0.25); } foreach (int itemtype in Dimensions.DeeperDungeon.ShadowItems.Where(testby => testby > ItemID.Count)) { WR.Add(new LootBoxContents(itemtype, 1), 0.40); } loots.Add(WR.Get()); }
public CinematicCamera GetWeightedCamera() { CinematicShotType randomShotType = WeightedRandom.Get(shotWeights); switch (randomShotType) { default: case CinematicShotType.Level: { // Get a mounted camera if there are no level cameras available. return(GetWeightedLevelCamera() ?? GetBestMountedCamera(WorldObjectManager.Instance.PlayerDriver, null)); } case CinematicShotType.Mounted: { return(GetBestMountedCamera(WorldObjectManager.Instance.PlayerDriver, null)); } } }
public static void Initialize() { Requests = new List <QuestInstance>(); PostedQuests = new List <QuestInstance>(); ActiveQuests = new Dictionary <QuestInstance, HeroInstance[]>(); m_QuestAmountChoser = new WeightedRandom <int>( new int[3] { 1, 2, 3 }, new int[3] { 1, 3, 1 }); DayManager.Instance.OnNextDay += NextDay; GenerateStartingQuests(); }
public override string GetChat() { WeightedRandom <string> chats = new WeightedRandom <string>(); const int count = 6; for (int i = 1; i < count + 1; i++) { chats.Add(Language.GetTextValue("Mods.PboneUtils.TownChat.Miner." + i)); } if (Main.hardMode) { chats.Add(Language.GetTextValue("Mods.PboneUtils.TownChat.Miner.HardmodeOnly")); } return(chats); }
public override string GetChat() { WeightedRandom <string> chat = new WeightedRandom <string>(); chat.Add("Greetings, " + Main.LocalPlayer.name + "! How may I aid you?"); chat.Add("Please, do not be frightened by my appearance. I may be a ghost, but I am not evil."); chat.Add("We may look different, but inside... We have the same 'heart' as you."); //chat.Add("Be cautious of my brethren in our ancient ruins, for they may put your mettle to the test."); int wdoctor = NPC.FindFirstNPC(NPCID.WitchDoctor); if (wdoctor >= 0) { chat.Add(Main.npc[wdoctor].GivenName + " keeps shaking his witchcraft 'things' at me whenever I come near him. Could ask him to stop?", 0.5); } return(chat); }
protected override void FillLootBox(WeightedRandom <LootBoxContents> WR) { WR.Add(new LootBoxContents(ItemID.PaladinsShield, 1)); WR.Add(new LootBoxContents(ItemID.CellPhone, 1)); WR.Add(new LootBoxContents(ItemID.CosmicCarKey, 1)); WR.Add(new LootBoxContents(ItemID.TerraBlade, 1)); WR.Add(new LootBoxContents(ItemID.SnowmanCannon, 1)); WR.Add(new LootBoxContents(ItemID.BlizzardStaff, 1)); WR.Add(new LootBoxContents(ItemID.DefenderMedal, 50), 1); WR.Add(new LootBoxContents(ItemID.ReindeerBells, 1)); WR.Add(new LootBoxContents(ItemID.PaladinsShield, 1)); WR.Add(new LootBoxContents(ItemID.DefendersForge, 1)); WR.Add(new LootBoxContents(ItemID.FireGauntlet, 1)); WR.Add(new LootBoxContents(ItemID.DestroyerEmblem, 1)); WR.Add(new LootBoxContents(ItemID.CelestialShell, 1)); WR.Add(new LootBoxContents(ItemID.AnkhShield, 1)); loots.Add(WR.Get()); }
public override string GetChat() { WeightedRandom <string> chat = new WeightedRandom <string>(); int partyGirl = NPC.FindFirstNPC(NPCID.PartyGirl); if (partyGirl >= 0 && Main.rand.NextBool(4)) { chat.Add("Can you please tell " + Main.npc[partyGirl].GivenName + " to stop decorating my house with colors?"); } // These are things that the NPC has a chance of telling you when you talk to it. chat.Add("Sometimes I feel like I'm different from everyone else here."); chat.Add("What's your favorite color? My favorite colors are white and black."); chat.Add("What? I don't have any arms or legs? Oh, don't be ridiculous!"); chat.Add("This message has a weight of 5, meaning it appears 5 times more often.", 5.0); chat.Add("This message has a weight of 0.1, meaning it appears 10 times as rare.", 0.1); return(chat); // chat is implicitly cast to a string. }
// Consider using this alternate approach to choosing a random thing. Very useful for a variety of use cases. // The WeightedRandom class needs "using Terraria.Utilities;" to use public override string GetChat() { WeightedRandom <string> chat = new WeightedRandom <string>(); chat.Add("Such a wonderful shop, the Stonework Rose."); chat.Add("You must be the mayor!"); if (!Main.dayTime) { chat.Add("Midnight coffee is the best coffee."); } if (Main.raining) { chat.Add("Rain just makes the coffee that much better."); chat.Add("I'm not sure how I plan to get home in this weather."); } return(chat); // chat is implicitly cast to a string. You can also do "return chat.Get();" if that makes you feel better }
public static void AddDropTable(Player player, WeightedRandom <int> table, Dictionary <int, int> stacks = null) { if (table > 0) { if (stacks == null) { player.QuickSpawnItem(table); } else if (stacks.TryGetValue(table, out int stack)) { player.QuickSpawnItem(table, stack); } else { player.QuickSpawnItem(table); } } }
public override string GetChat() { WeightedRandom <string> text = new WeightedRandom <string>(Main.rand); text.Add("Science rules!"); text.Add("Inertia is a property of matter."); text.Add("Consider the following: buying from my shop!"); text.Add("What? No, I'm not going to talk about that. Science is about solving problems, not about discussing philosophy!"); int wizard = NPC.FindFirstNPC(NPCID.Wizard); if (wizard >= 0 && Main.rand.NextBool(4)) { text.Add($"Can you tell {Main.npc[wizard].GivenName} to stop giving me his weird potions?"); } int guide = NPC.FindFirstNPC(NPCID.Guide); if (guide >= 0 && NPC.downedBoss3 && !Main.hardMode && Main.rand.NextBool(4)) { text.Add($"Hmm... {Main.npc[guide].GivenName} seems distressed about something. I wonder what it could be?"); } int witchDoctor = NPC.FindFirstNPC(NPCID.WitchDoctor); if (witchDoctor >= 0 && Main.rand.NextBool(4)) { text.Add($"I keep trying to tell {Main.npc[witchDoctor].GivenName} that I don't believe his voodoo mumbo-jumbo, but he just won't seem to listen!"); } int barkeep = NPC.FindFirstNPC(NPCID.DD2Bartender); if (barkeep >= 0 && Main.rand.NextBool(4)) { text.Add("There has to be some sort of scientific reason behind the portals created by the Old One's Army, there just has to be! I refuse to believe that it's magic!"); } if (Main.LocalPlayer.HasItem(ItemID.PortalGun)) { text.Add("That's an interesting... tool you've got there. From Apple-ture Labs you say? Now that's thinking with portals!"); } return(text.Get()); }
public RandomByLastfmSimilarArtists () : base("lastfm_shuffle_similar_artists") { Label = AddinManager.CurrentLocalizer.GetString ("Shuffle by similar Artists (via Lastfm)"); Adverb = AddinManager.CurrentLocalizer.GetString ("by similar artists"); Description = AddinManager.CurrentLocalizer.GetString ("Play songs similar to those already played (via Lastfm)"); lock (initiated_lock) { instanceCount++; if (!initiated) { ServiceManager.PlayerEngine.ConnectEvent (RandomByLastfmSimilarArtists.OnPlayerEvent, PlayerEvent.StateChange); initiated = true; weightedRandom = new WeightedRandom<int> (); processedArtists = new List<int> (); } } Condition = "CoreArtists.ArtistID = ?"; OrderBy = "RANDOM()"; }
public RandomByLastfmUserTopArtists() : base("lastfm_shuffle_topartists") { Label = AddinManager.CurrentLocalizer.GetString ("Shuffle by your Top Artists (via Lastfm)"); Adverb = AddinManager.CurrentLocalizer.GetString ("by your top artists"); Description = AddinManager.CurrentLocalizer.GetString ("Play songs from your Top Artists (via Lastfm)"); Condition = "CoreArtists.ArtistID = ?"; OrderBy = "RANDOM()"; lock (initiated_lock) { instanceCount++; if (!initiated) { ServiceManager.PlayerEngine.ConnectEvent (RandomByLastfmUserTopArtists.OnPlayerEvent, PlayerEvent.StateChange); initiated = true; Log.Debug ("RandomByLastfmUserTopArtists: Initialising List"); weightedRandom = new WeightedRandom<int> (); } } }
private static void Main(string[] args) { #region Inconsequential locals const string id1 = "A"; const string id2 = "B"; const string id3 = "C"; const int weight1 = 10; const int weight2 = 50; const int weight3 = 40; const int numIterations = 100000; var id1Returned = 0; var id2Returned = 0; var id3Returned = 0; #endregion // // Initialize an instance of WeightedRandom with an array of WeightedRandomItems. // var items = new [] { new WeightedRandomItem<string> (id1, weight1), new WeightedRandomItem<string> (id2, weight2), new WeightedRandomItem<string> (id3, weight3) }; var weightedRandom = new WeightedRandom<string>(items); // // Call weightedRandom.Next() a bunch of times to demonstrate that, over time, the // items are returned according to their weighted distribution. // for (int ix = 0; ix < numIterations; ix++) { var id = weightedRandom.Next(); if (id1.Equals(id, StringComparison.OrdinalIgnoreCase)) { id1Returned++; } else if (id2.Equals(id, StringComparison.OrdinalIgnoreCase)) { id2Returned++; } else if (id3.Equals(id, StringComparison.OrdinalIgnoreCase)) { id3Returned++; } else { throw new Exception("An ID was returned from WeightedRandom.Next() that should not have been: " + id); } } // // Display the results. // Console.WriteLine("Number of iterations: {0}", numIterations); Console.WriteLine("\t{0} selected {1} times, or {2}% of the time (weight: {3})", id1, id1Returned, Percentage(id1Returned, numIterations), weight1); Console.WriteLine("\t{0} selected {1} times, or {2}% of the time (weight: {3})", id2, id2Returned, Percentage(id2Returned, numIterations), weight2); Console.WriteLine("\t{0} selected {1} times, or {2}% of the time (weight: {3})", id3, id3Returned, Percentage(id3Returned, numIterations), weight3); Console.WriteLine("Number of selections: {0}", id1Returned + id2Returned + id3Returned); Console.WriteLine("Press ENTER to quit the application"); Console.ReadLine(); }
private WeightedRandom<XElement> InitRandom(string elementName) { WeightedRandom<XElement> random = new WeightedRandom<XElement>(); foreach(XElement role in profile.Element(elementName).Descendants("Role")) { int weight = Int32.Parse(role.Element("Weight").Value); random.AddValue(weight, role); } return random; }
public void Dispose() { if (disposed) return; ThreadAssist.ProxyToMain (delegate { lock (initiated_lock) { initiated = false; instanceCount--; if (instanceCount < 1) { weightedRandom = null; } } disposed = true; }); }
void prepare() { mGroupsHaveDepth = false; m_RepeatingGroups.MakePositive(); m_RepeatingGroups.Clamp(0, GroupCount - 1); // Groups if (mGroupBag == null) mGroupBag = new WeightedRandom<int>(); else mGroupBag.Clear(); if (RepeatingOrder == CurvyRepeatingOrderEnum.Random) { for (int g = FirstRepeating; g <= LastRepeating; g++) mGroupBag.Add(g, (int)(Groups[g].Weight * 10)); } // Prepare Groups & ItemBags for (int g = 0; g < Groups.Count; g++) { Groups[g].PrepareINTERNAL(); mGroupsHaveDepth = mGroupsHaveDepth || (getMinGroupDepth(Groups[g]) > 0); } }
public void Dispose () { if (disposed) return; ThreadAssist.ProxyToMain (delegate { ServiceManager.PlayerEngine.DisconnectEvent (RandomByLastfmSimilarArtists.OnPlayerEvent); lock (initiated_lock) { initiated = false; instanceCount--; if (instanceCount < 1) { weightedRandom = null; processedArtists = null; } } disposed = true; }); }