/// <summary>
        /// Gets available hint strings
        /// </summary>
        /// <remarks>Adapted from vimium to give a consistent experience, see https://github.com/philc/vimium/blob/master/content_scripts/link_hints.coffee </remarks>
        /// <param name="hintCount">The number of hints</param>
        /// <returns>A list of hint strings</returns>
        public IList<string> GetHintStrings(int hintCount)
        {
            var hintCharacters = new[] { 's', 'a', 'd', 'f', 'j', 'k', 'l', 'e', 'w', 'c', 'm', 'p', 'g', 'h' };
            var digitsNeeded = (int)Math.Ceiling(Math.Log(hintCount) / Math.Log(hintCharacters.Length));

            var shortHintCount = Math.Floor((Math.Pow(hintCharacters.Length, digitsNeeded) - hintCount) / hintCharacters.Length);
            var longHintCount = hintCount - shortHintCount;

            var hintStrings = new List<string>();

            if (digitsNeeded > 1)
            {
                for (var i = 0; i < shortHintCount; ++i)
                {
                    hintStrings.Add(NumberToHintString(i, hintCharacters, digitsNeeded - 1));
                }
            }

            var start = (int)(shortHintCount * hintCharacters.Length);
            for (var i = start; i < (start + longHintCount); ++i)
            {
                hintStrings.Add(NumberToHintString(i, hintCharacters, digitsNeeded));
            }

            // Note that shuffle is lazy evaluated. Sigh.
            return hintStrings.Shuffle().ToList();
        }
        public void AddWords(params string[] words)
        {
            //var placers = new List<WordPlacers.WordPlacer>{new WordPlacers.Diagonal(),
            //                                               new WordPlacers.Vertical(),
            //                                               new WordPlacers.Horizontal(),
            //                                               new WordPlacers.Reversed(new WordPlacers.Diagonal()),
            //                                               new WordPlacers.Reversed(new WordPlacers.Vertical()),
            //                                               new WordPlacers.Reversed(new WordPlacers.Horizontal()),
            //                                               };

            var placers = new List<WordPlacers.WordPlacer> { new WordPlacers.Horizontal() };

            foreach (var currentWord in words)
            {
                placers.Shuffle();

                foreach (var placer in placers)
                {
                    var result = placer.TryPlaceWord(currentWord, this);
                    if(result!=null)
                    {
                        Console.WriteLine("placed $result->word with {$result->direction} at X:{$result->x} Y:{$result->y}<br/>");
                        break;
                    }
                }
            }
        }
Example #3
0
        public void Randomize(Patch patch, Random r)
        {
            // Create list of default teleporter position values
            List<byte[]> coords = new List<byte[]>
            {
                new byte[]{ 0x20, 0x3B }, // Teleporter X, Y (top-left)
                new byte[]{ 0x20, 0x7B },
                new byte[]{ 0x20, 0xBB },
                new byte[]{ 0x70, 0xBB },
                new byte[]{ 0x90, 0xBB },
                new byte[]{ 0xE0, 0x3B },
                new byte[]{ 0xE0, 0x7B },
                new byte[]{ 0xE0, 0xBB }
            };

            // Randomize them
            coords.Shuffle(r);

            // Write the new x-coordinates
            for (int i = 0; i < coords.Count; i++)
            {
                byte[] location = coords[i];
                patch.Add((int)(EMiscAddresses.WarpXCoordinateStartAddress + i), location[0], String.Format("Teleporter {0} X-Pos", i));
            }

            // Write the new y-coordinates
            for (int i = 0; i < coords.Count; i++)
            {
                byte[] location = coords[i];
                patch.Add((int)(EMiscAddresses.WarpYCoordinateStartAddress + i), location[1], String.Format("Teleporter {0} Y-Pos", i));
            }

            // These values will be copied over to $04b0 (y) and $0470 (x), which will be checked
            // for in real time to determine where Mega will teleport to
        }
        public IList<string> GetDayActivity(IList<string> zoo, string killer)
        {
            if (!zoo.Contains(killer))
            {
                return new List<string>();
            }

            var herring = new List<string>(GameResources.Herrings);
            var goodTraits = new List<string>(GameResources.GoodTraits);
            var badTraits = new List<string>(GameResources.BadTraits);
            herring.Shuffle();
            goodTraits.Shuffle();
            badTraits.Shuffle();

            // good and bad traits
            int badIndex = 0;
            int goodIndex = 0;
            var clues = zoo.Select(x =>
                                {
                                    double chance = x == killer ? ChanceBadKillerTrait : ChanceBadFodderTrait;
                                    string trait = Extensions.RandomGenerator.Next(0, 999)/1000.0 < chance
                                        ? badTraits[badIndex++]
                                        : goodTraits[goodIndex++];
                                    return String.Format(trait, x);
                                }).ToList();

            // herrings
            int herringIndex = 0;
            clues.AddRange(zoo.Select(x => String.Format(herring[herringIndex++], x)));

            clues.Shuffle();

            return clues;
        }
Example #5
0
        public DataHolder()
        {
            phrases = new List<Phrase> ();

            phrases.Add (new Phrase ("USP", false));
            phrases.Add (new Phrase ("Micro services", false));
            phrases.Add (new Phrase ("Win-Win", false));
            phrases.Add (new Phrase ("Time to market", false));
            phrases.Add (new Phrase ("Perfor-mance", false));
            phrases.Add (new Phrase ("Scalable", false));
            phrases.Add (new Phrase ("Portfolio", false));
            phrases.Add (new Phrase ("24/7", false));
            phrases.Add (new Phrase ("New econo-my", false));
            phrases.Add (new Phrase ("Niche", false));
            phrases.Add (new Phrase ("Upside", false));
            phrases.Add (new Phrase ("Revenue", false));
            phrases.Add (new Phrase ("Supply chain", false));
            phrases.Add (new Phrase ("Call", false));
            phrases.Add (new Phrase ("Web 2.0", false));
            phrases.Add (new Phrase ("The new Face-book", false));
            phrases.Add (new Phrase ("Market share", false));
            phrases.Add (new Phrase ("Stake-holder", false));
            phrases.Add (new Phrase ("Inves-tors", false));
            phrases.Add (new Phrase ("VC", false));
            phrases.Add (new Phrase ("Burn rate", false));
            phrases.Add (new Phrase ("Work group", false));
            phrases.Add (new Phrase ("Market leader", false));
            phrases.Add (new Phrase ("Work load", false));
            phrases.Add (new Phrase ("Work-Life balance", false));

            phrases.Shuffle ();

            Current = this;
        }
        public static SuggestedTournamentRound CreateRandomRound(List<Player> players)
        {
            players.Shuffle();
            var round = new SuggestedTournamentRound();

            var playersSittingOut = CalculatePlayersSittingOutNext(players);
            round.AddPlayersSittingOut(playersSittingOut);
            var playingPlayers = players.Except(playersSittingOut).ToList();
            List<Player> remainingPlayers;
            var match = SuggestedMatch.CreateMatchFromFirstFirstFourPlayers(playingPlayers, out remainingPlayers);
            while (match != null)
            {
                round.AddMatch(match);
                playingPlayers = remainingPlayers;
                match = SuggestedMatch.CreateMatchFromFirstFirstFourPlayers(playingPlayers, out remainingPlayers);

            }

            if (remainingPlayers.Count != 0)
            {
                throw new Exception("Was not expecting any remainig players!");
            }

            return round;
        }
        public Level Build(int dimension)
        {
            if (dimension == 0)
                return _Level;
            var mapCells = LevelGenerator._BuildMaze(dimension);
            var rooms = new List<MazeCell>();
            var aisles = new List<MazeCell>();
            foreach (var cell in mapCells)
            {
                var walls = cell.Walls;
                var center = cell.GetPosition(_Width, _Height);
                foreach (var wall in walls)
                {
                    var dir = _WallToDirection(wall);
                    _Level.Add(new LevelUnit(Data.LEVEL_UNIT.WALL , center, dir));
                }

                if (cell.IsRoom())
                {
                    rooms.Add(cell);
                }
                else if (cell.HaveWall())
                {
                    aisles.Add(cell);
                }
            }

            _BuildScene(rooms.Shuffle().ToArray(), aisles.Shuffle().ToArray());

            return _Level;
        }
Example #8
0
        public List<Square> GetMove(Square square)
        {
            var movesList = new List<Square>();

            var move = HorizontalLeftUp(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = HorizontalLeftDown(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = HorizontalRightUp(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = HorizontalRightDown(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalUpLeft(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalUpRight(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalDownLeft(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalDownRight(square);
            if (IsSquareValid(move)) movesList.Add(move);

            movesList.RemoveAll(Visited);

            // randomize the order of a list to provide various detours each time
            movesList.Shuffle();

            return movesList;
        }
Example #9
0
        /// <summary>Partition dataset user- and item-wise for parallel processing</summary>
        /// <remarks>
        /// Literature:
        /// <list type="bullet">
        ///   <item><description>
        ///     Rainer Gemulla, Peter J. Haas, Erik Nijkamp, Yannis Sismanis:
        ///     Large-Scale Matrix Factorization with Distributed Stochastic Gradient Descent.
        ///     KDD 2011.
        ///     http://www.mpi-inf.mpg.de/~rgemulla/publications/gemulla11dsgd.pdf
        ///   </description></item>
        /// </list>
        /// </remarks>
        /// <returns>a two-dimensional array of index lists, each entry corresponds to one block entry</returns>
        /// <param name='dataset'>a feedback dataset</param>
        /// <param name='num_groups'>the number of groups both users and items are partitioned into</param>
        public static IList<int>[,] PartitionUsersAndItems(this IDataSet dataset, int num_groups)
        {
            // divide rating matrix into blocks
            var user_permutation = new List<int>(Enumerable.Range(0, dataset.MaxUserID + 1));
            var item_permutation = new List<int>(Enumerable.Range(0, dataset.MaxItemID + 1));
            user_permutation.Shuffle();
            item_permutation.Shuffle();

            var blocks = new IList<int>[num_groups, num_groups];
            for (int i = 0; i < num_groups; i++)
                for (int j = 0; j < num_groups; j++)
                    blocks[i, j] = new List<int>();

            for (int index = 0; index < dataset.Count; index++)
            {
                int u = dataset.Users[index];
                int i = dataset.Items[index];

                blocks[user_permutation[u] % num_groups, item_permutation[i] % num_groups].Add(index);
            }

            // randomize index sequences inside the blocks
            for (int i = 0; i < num_groups; i++)
                for (int j = 0; j < num_groups; j++)
                    blocks[i, j].Shuffle();

            return blocks;
        }
Example #10
0
        private static List<Card> GenerateStartDeck()
        {
            List<Card> startDeck = new List<Card>();
            startDeck.AddRange(GetCardsOfType(54, CardType.Hero, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.ElementalAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.PowerAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.ShadowAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.LightAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.TimeAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.SkillAura, true));
            startDeck.AddRange(GetCardsOfType(171, CardType.Action, false));
            startDeck.AddRange(GetCardsOfType(108, CardType.Item, true));
            startDeck.AddRange(GetCardsOfType(100, CardType.Spell, true));
            startDeck.AddRange(GetCardsOfType(60, CardType.Quest, false));
            startDeck.AddRange(GetCardsOfType(8, CardType.Boss, false));
            startDeck.AddRange(GetCardsOfType(15, CardType.Mercenary, false));
            startDeck.AddRange(GetCardsOfType(15, CardType.Mercenary, false));
            startDeck.Add(new Slime());
            startDeck.Add(new Slime());
            startDeck.Add(new Slime());
            startDeck.Add(new Slime());
            startDeck.Add(new CaptainFalcon());

            startDeck.Shuffle();

            return startDeck;
        }
        private List<Chromosom> GetListOfChromosomsUsinRuletteMethod(List<Chromosom> population)
        {
            double sumOfAllChromosomsFitnessValues = population.Sum(x => x.SurivatePoints);
            double meanOfChromosomsFitnessValues = sumOfAllChromosomsFitnessValues / population.Count;

            List<Chromosom> tmpPopulation = new List<Chromosom>(population.Count);

            foreach (var chromosom in population)
            {
                int numberOfChromosomsInNewGeneration = (int)Math.Round(chromosom.SurivatePoints / meanOfChromosomsFitnessValues);
                Console.WriteLine("Chomosom: {0} is going to be add {1}-times to new generation", chromosom, numberOfChromosomsInNewGeneration);
                for (int i = 0; i < numberOfChromosomsInNewGeneration; i++)
                {
                    tmpPopulation.Add(chromosom);
                }
            }

            int countDiffence = tmpPopulation.Count - population.Count;
            
            if (countDiffence < 0 )
            {
                var sortedPopulation = population.OrderByDescending(chromosom => chromosom.SurivatePoints);
                tmpPopulation.AddRange(sortedPopulation.Take(Math.Abs(countDiffence)));
            }
            else if (tmpPopulation.Count - population.Count > 0)
            {
                tmpPopulation = tmpPopulation.Shuffle().Take(population.Count).ToList();
            }

            return tmpPopulation;
            // do cross
        }
        public void Mutate(Genotype genotype, MutationResults results)
        {
            var neuronIndexA = Random.Range(0, genotype.NeuronCount);
              var neuronGeneA = genotype.NeuronGenes.ElementAt(neuronIndexA);

              var candidates = new List<NeuronGene>(genotype.NeuronGenes);
              candidates.Shuffle();

              NeuronGene neuronGeneB = default(NeuronGene);
              bool foundNeuron = false;
              for (var i = 0; i < candidates.Count; i++) {
            neuronGeneB = candidates[i];

            var exists = genotype.SynapseGenes.Any(s =>
              neuronGeneA.InnovationId == s.fromNeuronId &&
              neuronGeneB.InnovationId == s.toNeuronId);

            if (!exists) {
              foundNeuron = true;
              break;
            }
              }

              if (foundNeuron) {
            var synapseInnovationId = innovations.GetSynapseInnovationId(neuronGeneA.InnovationId, neuronGeneB.InnovationId);
            var synapseGene = new SynapseGene(synapseInnovationId, neuronGeneA.InnovationId, neuronGeneB.InnovationId, true);

            var synapseGenes = new GeneList<SynapseGene>(genotype.SynapseGenes);
            synapseGenes.Add(synapseGene);
            genotype.SynapseGenes = synapseGenes;

            results.addedSynapses += 1;
              }
        }
Example #13
0
	public static LGcharacter CharacterGen () 
	{
		LGcharacter Baby = LGcharacter.CreateInstance<LGcharacter>();
		List<int> toGen = new List<int>();
		List<int> lastPass = new List<int> ();
		for (int i = 0; i < (int)TraitType.COUNT; i++) {
			Baby.SetTrait ((TraitType)i, kMinTrait);
			toGen.Add (i);
		}
		toGen.Shuffle ();
		int toSpend = kMaxGenPoints;
		while (toGen.Count > 0) {
			TraitType type = (TraitType)toGen [0];
			lastPass.Add (toGen [0]);
			toGen.RemoveAt (0);
			double gaussRoll = RNGesus.PraiseGauss (kMeanTrait, kTraitDev);
			int newVal = (int)gaussRoll;
			if (newVal > kMaxTrait-1) {
				newVal = kMaxTrait-1;
			}
			if (newVal < kMinTrait) {
				newVal = kMinTrait;
			}
			if (newVal > toSpend) {
				newVal = toSpend;
			}
			if (Baby.AddTrait (type, newVal)) {
				toSpend -= newVal;
			}
		}
		// Do one last pass to spend remaining points randomly.
		// Removing stats that are too full. 
		// TODO: Instead, spend these on specialized traits based on the number of unspent points
		/*
		while (toSpend > 0 && lastPass.Count > 0) {
			int roll = RNGesus.Praise (0, lastPass.Count-1);
			if (Baby.AddTrait ((TraitType)lastPass[roll], 1)) {
				toSpend--;
			} else {
				lastPass.RemoveAt (roll);
			}
		}
		*/
		// Set stats to their default values (max for most, min for Toxicity)
		for (int i = 0; i < (int)StatusType.COUNT; i++) {
			Baby.SetStat ((StatusType)i, kMaxStatus);
		}
		Baby.SetStat (StatusType.TOXICITY, kMinStatus);

		// Roll Random Skills
		Dictionary<uint, LGskill> genSkill = LGskillData.Skills;
		Baby._AttackSkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];
		Baby._ClassSkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];
		Baby._UtilitySkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];
		Baby._AugmentSkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];


		return Baby;
	}
Example #14
0
        public void Shuffle_ShouldPreserveOriginalList()
        {
            var list = new List<int> {1, 2, 3, 4};
            var expected = new List<int>(list);
            list.Shuffle(RandomProvider.GetRandom(2));

            Assert.Equal(expected, list);
        }
Example #15
0
 public void Shuffle_OrderChanges()
 {
     // In theory we could get back the exact same order- really unlikely, particularly with larger collections
     int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     List<int> items = new List<int>(source);
     items.Shuffle();
     items.Should().NotEqual(source);
 }
 public OneHotRecordProvider(GPUModule gpuModule, List<OneHotRecordReadOnly> records, string id = "", bool shuffleEveryEpoch = false)
 {
     Id = id;
     _records = records;
     GpuModule = gpuModule;
     _shuffle = shuffleEveryEpoch;
     if (_shuffle) _records.Shuffle();
 }
Example #17
0
        public void ListExtensionShuffle_CommonList_EndWithNoExceptions_Test()
        {
            var list = new List<string> {"4","2","7","5","1"};

            list.Shuffle();

            Assert.NotNull(list);
            Assert.Equal(5,list.Count);
        }
Example #18
0
        public void Shuffle_ShouldShuffle()
        {
            var list = new List<int> { 1, 2, 3, 4 };
            var result = list.Shuffle(RandomProvider.GetRandom(2));

            Assert.NotNull(result);
            Assert.Equal(list, result.OrderBy(i => i).ToList());
            Assert.NotEqual(list, result);
        }
 private IEnumerable<List<int>> GetRandomVectors(int n, FastRandom rand) {
   for (int i = 0; i < n; i++) {
     int length = rand.Next(1, 50);
     List<int> cur = new List<int>(length) { 0 };
     for (int j = 0; j < length - 1; j++) {
       cur.Add(rand.Next(-50, 50));
     }
     yield return cur.Shuffle(rand).ToList();
   }
 }
Example #20
0
 /// <summary>
 /// Generates a random route.
 /// </summary>
 /// <param name="problem"></param>
 /// <returns></returns>
 public static IRoute DoSolveStatic(IProblem problem)
 {
     List<int> customers = new List<int>();
     for (int customer = 0; customer < problem.Size; customer++)
     {
         customers.Add(customer);
     }
     customers.Shuffle<int>();
     return DynamicAsymmetricRoute.CreateFrom(customers);
 }
Example #21
0
 public Answersheet(Question q)
 {
     SelectedQuestion = q;
     Answerkeys = new ObservableCollection<Pair<string, bool>>();
     GivenAnswers = new ObservableCollection<string>();
     List<Pair<string, bool>> tAnswer = new List<Pair<string, bool>>(q.Answers);
     tAnswer.Shuffle();
     foreach (Pair<string, bool> answer in tAnswer)
         Answerkeys.Add(new Pair<string, bool>(answer.First, false));
 }
Example #22
0
		protected override async Task<bool> Main()
		{
			if (startZoneId != WorldManager.ZoneId)
			{
				return isDone = true;
			}

			if (ExProfileBehavior.Me.Distance(Location) <= Distance)
			{
				return isDone = true;
			}

			if (HotSpots != null)
			{
				if (Type == MoveToType.Auto)
				{
					Type = MoveToType.RandomPointWithin;
				}

				var locations = new List<HotSpot>(HotSpots);
				if (Location != Vector3.Zero)
				{
					locations.Add(new HotSpot(Location, Distance) {Name = Name});
				}

				destination = locations.Shuffle().First();

				Logger.Verbose(Localization.Localization.ExMoveTo_Random, Location);
			}
			else
			{
				if (Type == MoveToType.Auto)
				{
					Type = MoveToType.StopWithinRange;
				}

				destination = new HotSpot(Location, Distance) {Name = Name};
			}

			var name = !string.IsNullOrWhiteSpace(destination.Name) ? "[" + destination.Name + "] " : string.Empty;

			StatusText = string.Format(Localization.Localization.ExMoveTo_Move, name, destination, Type);

			switch (Type)
			{
				case MoveToType.StopWithinRange:
					await destination.MoveTo(UseMesh);
					break;
				case MoveToType.RandomPointWithin:
					await destination.MoveToPointWithin();
					break;
			}

			return isDone = true;
		}
        public Meta Load()
        {
            List<string> metaServerList = metaServerLocator.GetMetaServerList();
            if (metaServerList == null || metaServerList.Count == 0)
            {
                throw new Exception("No meta server found.");
            }

            List<String> ipPorts = new List<String>(metaServerList);
            ipPorts.Shuffle();

            foreach (string ipPort in ipPorts)
            {
                log.Debug(string.Format("Loading meta from server: {0}", ipPort));

                try
                {
                    string url = string.Format("http://{0}/meta", ipPort);
                    if (metaCache.ReadFullFence() != null)
                    {
                        url += "?version=" + metaCache.ReadFullFence().Version;
                    }

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Timeout = config.MetaServerConnectTimeoutInMills + config.MetaServerReadTimeoutInMills;

                    using (HttpWebResponse res = (HttpWebResponse)req.BetterGetResponse())
                    {
                        HttpStatusCode statusCode = res.StatusCode;
                        if (statusCode == HttpStatusCode.OK)
                        {
                            using (var stream = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
                            {
                                string responseContent = stream.ReadToEnd();
                                JsonSerializerSettings settings = new JsonSerializerSettings();
                                settings.NullValueHandling = NullValueHandling.Ignore;
                                metaCache.WriteFullFence(JsonConvert.DeserializeObject<Meta>(responseContent, settings));
                                return metaCache.ReadFullFence();
                            }
                        }
                        else if (statusCode == HttpStatusCode.NotModified)
                        {
                            return metaCache.ReadFullFence();
                        }
                    }

                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
            throw new Exception(string.Format("Failed to load remote meta from {0}", ipPorts));
        }
Example #24
0
 public static Stack<PlayerColorEnum> GetColors()
 {
     Stack<PlayerColorEnum> colors = new Stack<PlayerColorEnum>();
     List<PlayerColorEnum> shuffleList = new List<PlayerColorEnum>();
     foreach (PlayerColorEnum color in Enum.GetValues(typeof(PlayerColorEnum)))
     {
         shuffleList.Add(color);
     }
     shuffleList.Shuffle();
     shuffleList.ForEach(color => colors.Push(color));
     return colors;
 }
 private IEnumerable<int> GenerateDiceCards()
 {
     var cards = new List<int>();
     foreach (var item in GameConstants.DiceRollNumber2Chance)
     {
         for (var i = 0; i < item.Value; ++i)
         {
             cards.Add(item.Key);
         }
     }
     return cards.Shuffle();
 }
        public static double CalculateHandValue(IList<Card> myHand, IList<Card> communityCards)
        {
            if (communityCards.Count == 0)
            {
                if ((int) myHand[0].Type < 5 && (int) myHand[1].Type < 5 && myHand[0].Type != myHand[1].Type)
                {
                    return 0;
                }
            }

            double wins = 0;

            Parallel.For(0, Settings.GameSimulationsCount, i =>
            //for (int i = 0; i < Settings.GameSimulationsCount; i++)
            {
                var player1Hand = new List<Card>(myHand);
                var player2Hand = new List<Card>();

                var remainingCommunityCards = new List<Card>();

                var deck = new List<Card>(Deck.AllCards);
                deck.CustomRemoveRange(myHand);
                deck.CustomRemoveRange(communityCards);
                deck = deck.Shuffle().ToList();

                //generate remaining community cards
                for (int j = 0; j < 5 - communityCards.Count; j++)
                {
                    remainingCommunityCards.Add(deck.Deal());
                }

                //add hole/community cards to the AI
                player1Hand.AddRange(communityCards);
                player1Hand.AddRange(remainingCommunityCards);

                //add cards to player2
                player2Hand.Add(deck.Deal());
                player2Hand.Add(deck.Deal());
                player2Hand.AddRange(communityCards);
                player2Hand.AddRange(remainingCommunityCards);

                //compare hands
                if (Helpers.CompareCards(player1Hand, player2Hand) == 1)
                {
                    lock (locker)
                    {
                        wins++;
                    }
                }
            });

            return wins / Settings.GameSimulationsCount;
        }
Example #27
0
        public static void DoWork(List<User> users, IMailer mailer)
        {
            var secrets = new List<User>();
            secrets.AddRange(users);

            //shuffle secrets:
            secrets = secrets.Shuffle(new Random(DateTime.Now.Millisecond)).ToList();

            //shuffle not perfect: check for mistakes
            while (GetError(secrets, users))
            {
                secrets = secrets.Shuffle(new Random(DateTime.Now.Millisecond)).ToList();
            }

            for (int i = 0; i < users.Count; i++)
            {
                var user = users[i];
                //Debug.WriteLine(string.Format("{0} to {1}", user.Email, secrets[i].Name));
                mailer.SendMail(user.Name, user.Email, secrets[i].Name, secrets[i].Wishes);
            }
        }
Example #28
0
    //protected override IEnumerable<int> GenerateTraining() {
    //  var x0 = new List<int>() { 1, 2, 3, 4, 5, 100 };
    //  x0.AddRange(ValueGenerator.SampleRandomWithoutRepetition(numbers, 44, rand));
    //  return x0;
    //}

    //protected override IEnumerable<int> GenerateTest() {
    //  return numbers.Except(GenerateTraining());
    //}

    //protected override Tuple<string[], string[]> GenerateInputOutput(IEnumerable<int> x0) {
    //  var input = x0.Select(x => x.ToString()).ToArray();
    //  var output = x0.Select(x => CalcSumOfSquares(x).ToString()).ToArray();
    //  return new Tuple<string[], string[]>(input, output);
    //}

    protected override Tuple<string[], string[]> GenerateInputOutput() {
      FastRandom rand = new FastRandom();
      var x0 = new List<int>() { 1, 2, 3, 4, 5, 100 };
      x0.AddRange(ValueGenerator.SampleRandomWithoutRepetition(numbers, 44, rand));

      x0 = x0.Shuffle(rand).ToList();

      x0.AddRange(numbers.Except(x0));

      var input = x0.Select(x => x.ToString()).ToArray();
      var output = x0.Select(x => CalcSumOfSquares(x).ToString()).ToArray();
      return new Tuple<string[], string[]>(input, output);
    }
Example #29
0
    public static List<Node> GetRandomNodesInRange(Vector3 position, float range)
    {
        List<Node> nodes = new List<Node>();
        Collider[] colliders = Physics.OverlapSphere(position,range) as Collider[];
        foreach(Collider collider in colliders) {
            if(collider.gameObject.tag == "Node") {
                nodes.Add (collider.gameObject.GetComponent<Node>()) ;

            }
        }
        nodes.Shuffle();
        return nodes;
    }
Example #30
0
 private static void BuildDeck() {
     Cards = new List<Card>(52);
     foreach (CardSuit s in GetValues(typeof(CardSuit)).Cast<CardSuit>()) {
         foreach (CardValue v in
             GetValues(typeof(CardValue)).Cast<CardValue>()) {
             Cards.Add(new Card(s,v) {
                 IsInPlay = false,
                 IsVisible = false
             });
         }
     }
     Cards.Shuffle();
 }