예제 #1
0
        public static void C5CX(string name, string type, int length, string output)
        {
            List<DmDPC> srcNumbers = null;
            if (length > 5)
            {
                srcNumbers = NumberCache.Instance.GetNumberList(type);
            }
            else
            {
                srcNumbers = NumberCache.Instance.GetNumberList("C5");
            }

            DmC5CXBiz biz = new DmC5CXBiz(name);
            List<DmC5CX> entities = new List<DmC5CX>(srcNumbers.Count * 56);
            foreach (var srcNumber in srcNumbers)
            {
                string number = srcNumber.Number.Replace(' ', ',');
                var cxNumbers = new Combinations<int>(number.ToList(), length > 5 ? 5 : length);
                foreach (var cxNumber in cxNumbers)
                {
                    string cx = NumberCache.Instance.GetNumberId(length > 5 ? "C5" : type, cxNumber.Format("D2", ","));
                    DmC5CX entity = new DmC5CX();
                    entity.C5 = (length > 5) ? cx : srcNumber.Id;
                    entity.CX = (length > 5) ? srcNumber.Id : cx;
                    entity.C5Number = (length > 5) ? cx.ToString(2, " ") : srcNumber.Number;
                    entity.CXNumber = (length > 5) ? srcNumber.Number : cx.ToString(2, " ");
                    entity.NumberType = type;
                    entities.Add(entity);
                }
            }
            biz.DataAccessor.Insert(entities, SqlInsertMethod.SqlBulkCopy);
        }
예제 #2
0
        private static IList<Card> FindSet(Table table)
        {
            // Get all 3 card combinations and sets there within
            // http://www.codeproject.com/KB/recipes/Combinatorics.aspx
            var combinations = new Combinations<Card>(table.Cards, 3);
            IEnumerable<IList<Card>> sets = combinations.Where(IsMatch);

            // Return the first set found, return null if no sets
            return sets.FirstOrDefault();
        }
예제 #3
0
 public void FindMatchingCombinationsAndReplaceCards()
 {
     var deck = new Deck();
     var table = new Table { Cards = deck.GetNext(12) };
     var combinations = new Combinations<Card>(table.Cards, 3);
     var sets = combinations.Where(IsMatch);
     var cards = sets.FirstOrDefault();
     Console.WriteLine(String.Format("Match found: {{{0} {1} {2}}}", cards[0], cards[1], cards[2]));
     ReplaceSetWithNewCards(deck, table, cards);
 }
예제 #4
0
 public static void C(string name, string type, int length, string output)
 {
     var c = new Combinations<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, length);
     if (output.Equals("txt"))
     {
         SaveToText(name, type, c);
         return;
     }
     SaveToDB(name, type, c);
 }
예제 #5
0
        protected IEnumerable<ComboPossibleScores> BaseAverageDecision(IEnumerable<Card> hand)
        {
            var handIter = new HashSet<Card>(hand);
            var combinations = new Combinations<Card>(handIter.ToList(), 4);
            var deck = new Deck();
            var possibleCardsCut = deck.Where(card => !handIter.Contains(card)).ToList();

            var comboPossibleScoreses = GetPossibleCombos(combinations, possibleCardsCut).ToList();
            return comboPossibleScoreses;
        }
예제 #6
0
 private IEnumerable<ComboPossibleScores> GetPossibleCombos(Combinations<Card> handCombinations, List<Card> possibleStarterCards)
 {
     return handCombinations.AsParallel().Select(combo =>
     {
         var possibleScores = possibleStarterCards
             .Select(cutCard => new ScoreWithCut { Cut = cutCard, Score = _scoreCalculator.CountShowScore(cutCard, combo).Score })
             .ToList();
         return new ComboPossibleScores(combo, possibleScores);
     });
 }
예제 #7
0
        public IEnumerable<Movement> FindMoves(Board board)
        {
            clearAllGuesses();

            int flagsLeft = 99;
            List<Block> unknown = board.getUnknownBlocks(out flagsLeft);

            if (flagsLeft > 8)
                yield break;

            List<Block> unsolvedBlocks = new List<Block>();
            foreach (var un in unknown)
                unsolvedBlocks.AddRange(new NeighborList(board.Grid, un).Where(i => i.State == BlockState.Value));
            unsolvedBlocks = unsolvedBlocks.Distinct().ToList();

            var flagCombinations = new Combinations<Block>(unknown, flagsLeft);

            // Remove any combinations that locally break the game board
            var validFlagCombinations = flagCombinations.Where(comb =>
            {
                foreach (var item in comb) item.SetGuess(GuessState.Flag, tempGuesses);
                bool valid = comb.All(c => board.isValidBlock(c));
                clearAllGuesses();
                return valid;
            }).ToList();

            // Remove any combinations taht globally break the game board
            for (int i = 0; i < validFlagCombinations.Count; i++)
            {
                clearAllGuesses();
                var comb = validFlagCombinations[i];
                foreach (var guess in comb)
                    guess.SetGuess(GuessState.Flag, tempGuesses);

                if (!isValidMacroGuess(board, unsolvedBlocks, comb))
                    validFlagCombinations.RemoveAt(i--);
            }

            clearAllGuesses();

            // Get any flags that present in all of the guess. These are guaranteed to be flags
            var validFlags = validFlagCombinations.Aggregate((l1, l2) => l1.Intersect(l2).ToList()).ToList();

            foreach (var flag in validFlags)
                yield return new Movement(flag, MoveTypes.SetFlag);

            foreach (var un in unknown)
            {
                if (validFlagCombinations.All(c => !c.Contains(un)))
                    yield return new Movement(un, MoveTypes.SetClear);
            }

            clearAllGuesses();
        }
예제 #8
0
        public void GetSetCombinations()
        {
            var deck = new Deck();
            var table = new Table { Cards = deck.GetNext(12) };

            Combinations<Card> combinations = new Combinations<Card>(table.Cards, 3);

            foreach (IList<Card> c in combinations)
            {
                Console.WriteLine(String.Format("{{{0} {1} {2}}}", c[0], c[1], c[2]));
            }
        }
예제 #9
0
        public static string GetBestHand(List<Card> listCards)
        {
            string bestHand="Nothing";
            int bestHandRank = 0;
            var allCombinations = new Combinations<Card>(listCards, 5);

            foreach (var hand in allCombinations)
            {
                if (IsStraightFlush(hand).Item2 > bestHandRank) { bestHand = IsStraightFlush(hand).Item1; bestHandRank = IsStraightFlush(hand).Item2; }
            }
            return bestHand;
        }
예제 #10
0
        public void CanMakeValidCombinations()
        {
            char[] inputSet = {'A', 'B', 'C', 'D'};

            var combinations = new Combinations<char>(inputSet, 3);
            string cformat = "Combinations of {{A B C D}} choose 3: size = {0}";
            Console.WriteLine(String.Format(cformat, combinations.Count));
            foreach (var c in combinations)
            {
                Console.WriteLine(String.Format("{{{0} {1} {2}}}", c[0], c[1], c[2]));
            }
        }
        /// <summary>
        /// 获取号码AC值, 一组号码中所有两个号码相减,然后对所得的差求绝对值,
        /// 如果有相同的数字,则只保留一个,得到不同差值个数,
        /// AC值就等于不同差值个数减去r-1(r为投注号码数,在数字三型彩票中r为3)。
        /// </summary>
        /// <param name="digits">号码的各位数字集合</param>
        /// <returns>AC值</returns>
        public static int GetAC(this IList<int> digits)
        {
            if (digits.Count <= 1) return 0;

            int r = digits.Count;
            var comb = new Combinations<int>(digits, 2);
            var substracts = new List<int>(comb.Count);
            foreach (var number in comb)
            {
                substracts.Add(number.GetKuaDu());
            }
            return substracts.Distinct().Count() - (r - 1);
        }
예제 #12
0
        public void Generate_Combinations_of_3_Without_Repetition_On_6_Input_Items_Should_Create_20_Output_Items()
        {
            var integers = new List<int> {1, 2, 3, 4, 5, 6};

            var c = new Combinations<int>(integers, 3, GenerateOption.WithoutRepetition);

            foreach (var v in c)
            {
                System.Diagnostics.Debug.WriteLine(string.Join(",", v));
            }

            Assert.AreEqual(20, c.Count);
        }
 public void Combinations()
 {
     foreach (var i in Enumerable.Range(0, 1000))
     {
         foreach (int value in Enumerable.Range(1, _hand.Count))
         {
             var comboGen = new Combinations<Card>(_hand, value);
             foreach (var set in comboGen)
             {
                 Assert.True(set.Count > 0);
             }
         }
     }
 }
예제 #14
0
        public void FindFirstMatchingCombinations()
        {
            var deck = new Deck();
            var table = new Table {Cards = deck.GetNext(12)};

            var combinations = new Combinations<Card>(table.Cards, 3);

            foreach (IList<Card> c in combinations)
            {
                if (IsMatch(c))
                {
                    Console.WriteLine(String.Format("{{{0} {1} {2}}}", c[0], c[1], c[2]));
                    break;
                }
            }
        }
예제 #15
0
파일: Grid.cs 프로젝트: efiliba/WinRTSudoku
        public Grid(int columns, int rows)
        {
            this.columns = columns;
            this.rows = rows;

            subGrids = new SubGrid[rows][];
            for (int row = 0; row < rows; row++)
            {
                subGrids[row] = new SubGrid[columns];
                for (int column = 0; column < columns; column++)
                    subGrids[row][column] = new SubGrid(columns, rows, column, row);
            }

            totalSet = 0;
            combinations = new Combinations(columns * rows);
        }
예제 #16
0
 private void Create_Combinations()
 {
     combinationsList = new List<Combinations<string>> { };
     combinationsCounts = new List<long> { };
     combinationsTimeTaken = new List<long> { };
     Stopwatch time = Stopwatch.StartNew();
     for (int i = 1; i < 18; i++)
     {
         List<string> inputSet = new List<string> { };
         for (int j = 97; j < 101; j++) // chars from a to d
             inputSet.Add(((char)j).ToString());
         Combinations<string> combinations = new Combinations<string>(inputSet, i, GenerateOption.WithRepetition);
         combinationsList.Add(combinations);
         combinationsCounts.Add(combinations.Count);
     }
     time.Stop();
     combinationsTimeTaken.Add(time.ElapsedMilliseconds);
 }
예제 #17
0
        public IEnumerable<Card> DetermineCardsToThrow(IEnumerable<Card> hand)
        {
            var handList = hand.ToList();
            var combinations = new Combinations<Card>(handList, 4);

            var possibleCardsCut = _deck.Where(card => !handList.Contains(card)).ToList();

            var totalPossibleCombinations = combinations
                .SelectMany(combo => possibleCardsCut.Select(cutCard =>
                {
                    var possibleCombo = new List<Card>(combo) {cutCard};
                    var comboScore = _scoreCalculator.CountShowScore(cutCard, combo);
                    return new ComboScore(possibleCombo, comboScore.Score);
                }));

            var highestScoringCombo = totalPossibleCombinations.MaxBy(cs => cs.Score);
            return handList.Where(card => !highestScoringCombo.Combo.Contains(card));
        }
        // String names for each combination
        public static string getCombinationName(Combinations combinationID)
        {
            switch (combinationID)
            {
                case Combinations.WAVE_RIGHT_HAND_OVER_SHOULDER:
                    return "Waving right hand over shoulder";
                case Combinations.WAVE_RIGHT_HAND:
                    return "Waving right hand";
                case Combinations.CLIMBING_HANDS:
                    return "Climbing hands movement";
                case Combinations.THROWING_RIGHT:
                    return "Throwing with right hand";
                case Combinations.BALANCING:
                    return "Balancing";
                case Combinations.NUM_COMBINATIONS:
                    return "Invalid combination id";
            }

            return "Unknown combination id";
        }
예제 #19
0
        public SwapsModel Balance(ICollection<PlayerModel> blueTeam, ICollection<PlayerModel> redTeam)
        {
            if(blueTeam.Count + redTeam.Count != 10)
            {
                throw new ArgumentException("10 players required to balance the teams.");
            }

            int lowestRatingDiff = Int32.MaxValue;
            ICollection<PlayerModel> finalTeam1 = null;
            ICollection<PlayerModel> finalTeam2 = null;

            IList<PlayerModel> players = blueTeam.Concat(redTeam).ToList();
            
            Combinations<PlayerModel> combinations = new Combinations<PlayerModel>(players, 5);

            foreach(ICollection<PlayerModel> team1 in combinations)
            {
                ICollection<PlayerModel> team2 = GetOtherTeam(players, team1);

                int team1Rating = GetTeamRating(team1);
                int team2Rating = GetTeamRating(team2);

                if(Math.Abs(team1Rating - team2Rating) < lowestRatingDiff)
                {
                    lowestRatingDiff = Math.Abs(team1Rating - team2Rating);
                    finalTeam1 = team1;
                    finalTeam2 = team2;
                }
            }

            ICollection<PlayerModel> blueSwaps = CalculateSwaps(blueTeam, finalTeam1, finalTeam2);
            ICollection<PlayerModel> redSwaps = CalculateSwaps(redTeam, finalTeam1, finalTeam2);

            return new SwapsModel()
            {
                RatingDifference = lowestRatingDiff,
                BlueSwaps = blueSwaps,
                RedSwaps = redSwaps
            };
        }
예제 #20
0
 static void Main()
 {
     int n = GetValidInput("Enter the upper margin for the number list ( 1 to N ): ", 2);
     //build the array
     List<int> numbers = new List<int>();
     for (int i = 1; i <= n; i++)
     {
         numbers.Add(i);
     }
     //get the number of ellements to be combined
     int k = GetValidInput("Enter the number of elements to ne combined :", 1);
     //generate a combinations collection
     Combinations<int> combinations = new Combinations<int>(numbers, k);
     //print the elements in the collection
     foreach (IList<int> p in combinations)
     {
         foreach (var item in p)
         {
             Console.Write(item + " ");
         }
         Console.WriteLine();
     }
 }
예제 #21
0
        public override void Solve()
        {
            var allSets = new Combinations<int>(Enumerable.Range(1, 9).ToArray(), 4, GenerateOption.WithoutRepetition);

            int topMax = 0;
            IList<int> topSet = null;

            foreach (IList<int> set in allSets)
            {
                int setMax = GetResultsForSet(set);

                if (setMax >= topMax)
                {
                    topMax = setMax;
                    topSet = set;
                }
            }

            string result = "";
            foreach (int i in topSet)
                result += i.ToString();

            Verify(long.Parse(result));
        }
예제 #22
0
파일: frmModel.cs 프로젝트: wrbrooks/VB3
        /// <summary>
        /// Calculate the total number of combinations availabl for the selected number of independent variables
        /// </summary>
        private void SetCombinations()
        {
            int numVars = lbIndVariables.Items.Count;

            List<short> combList = new List<short>();
            short tmp = 0; ;
            for (int i = 0; i < numVars; i++)
            {
                ListItem li = (ListItem)lbIndVariables.Items[i];
                tmp = 1;
                tmp += Convert.ToInt16(li.ValueItem);
                combList.Add(tmp);
            }

            //long totalComb = 0;
            decimal totalComb = 0;
            Combinations<short> combinations = null;
            for (int i = 0; i < numVars; i++)
            {
                combinations = new Combinations<short>(combList.ToArray(), i, GenerateOption.WithoutRepetition);
                totalComb += combinations.Count;

            }

            string nModels = string.Empty;
            if (totalComb > 9999999999)
            {
                nModels = string.Format("{0:000e000}", totalComb);
            }
            else
            {

                if (totalComb < 0)
                {
                    //we've flipped the storage capacity (not of totalComb [decimal type good to 7.8(10)**28], something else)
                    //combinations.Count is only a long - probably this (max 9.2(10)**18)
                    nModels = " more than 9.2e018 ";
                }
                else
                {
                    //lblnModels.Text = string.Format("{0:#,###,###,###}", totalComb);
                    nModels = string.Format("{0:#,###,###,###}", totalComb);
                }
            }

            VBLogger.getLogger().logEvent("Total number of possible models: " + nModels,
                VBLogger.messageIntent.UserAndLogFile, VBLogger.targetSStrip.StatusStrip3);
        }
예제 #23
0
        private void WP_ProcessBar_Load()
        {
            //IL_0014: Unknown result type (might be due to invalid IL or missing references)
            //IL_0019: Unknown result type (might be due to invalid IL or missing references)
            //IL_001e: Unknown result type (might be due to invalid IL or missing references)
            //IL_0020: Unknown result type (might be due to invalid IL or missing references)
            //IL_0021: Unknown result type (might be due to invalid IL or missing references)
            //IL_0026: Unknown result type (might be due to invalid IL or missing references)
            //IL_002c: Unknown result type (might be due to invalid IL or missing references)
            //IL_0032: Unknown result type (might be due to invalid IL or missing references)
            //IL_0033: Unknown result type (might be due to invalid IL or missing references)
            //IL_0038: Unknown result type (might be due to invalid IL or missing references)
            //IL_003f: Unknown result type (might be due to invalid IL or missing references)
            //IL_0041: Unknown result type (might be due to invalid IL or missing references)
            //IL_0047: Unknown result type (might be due to invalid IL or missing references)
            //IL_0048: Unknown result type (might be due to invalid IL or missing references)
            //IL_0070: Unknown result type (might be due to invalid IL or missing references)
            //IL_0075: Unknown result type (might be due to invalid IL or missing references)
            //IL_0078: Unknown result type (might be due to invalid IL or missing references)
            //IL_00dc: Unknown result type (might be due to invalid IL or missing references)
            //IL_00de: Unknown result type (might be due to invalid IL or missing references)
            //IL_00e3: Unknown result type (might be due to invalid IL or missing references)
            //IL_00e8: Unknown result type (might be due to invalid IL or missing references)
            //IL_00eb: Unknown result type (might be due to invalid IL or missing references)
            //IL_00ee: Unknown result type (might be due to invalid IL or missing references)
            //IL_00fb: Unknown result type (might be due to invalid IL or missing references)
            //IL_0100: Unknown result type (might be due to invalid IL or missing references)
            //IL_0103: Unknown result type (might be due to invalid IL or missing references)
            //IL_0105: Expected O, but got Unknown
            //IL_010a: Unknown result type (might be due to invalid IL or missing references)
            //IL_010c: Unknown result type (might be due to invalid IL or missing references)
            //IL_011c: Unknown result type (might be due to invalid IL or missing references)
            //IL_011e: Unknown result type (might be due to invalid IL or missing references)
            //IL_0144: Unknown result type (might be due to invalid IL or missing references)
            //IL_0146: Unknown result type (might be due to invalid IL or missing references)
            //IL_014b: Unknown result type (might be due to invalid IL or missing references)
            //IL_014e: Unknown result type (might be due to invalid IL or missing references)
            //IL_0154: Unknown result type (might be due to invalid IL or missing references)
            //IL_0159: Unknown result type (might be due to invalid IL or missing references)
            //IL_015e: Unknown result type (might be due to invalid IL or missing references)
            //IL_0160: Unknown result type (might be due to invalid IL or missing references)
            //IL_0193: Unknown result type (might be due to invalid IL or missing references)
            //IL_019b: Unknown result type (might be due to invalid IL or missing references)
            //IL_01a3: Unknown result type (might be due to invalid IL or missing references)
            //IL_01ba: Unknown result type (might be due to invalid IL or missing references)
            //IL_01c2: Unknown result type (might be due to invalid IL or missing references)
            //IL_01ca: Unknown result type (might be due to invalid IL or missing references)
            //IL_0231: Unknown result type (might be due to invalid IL or missing references)
            //IL_023f: Unknown result type (might be due to invalid IL or missing references)
            //IL_0244: Unknown result type (might be due to invalid IL or missing references)
            this.progressBar1.Maximum = this.PB;
            Transaction val = this.I_trans = new Transaction(this.DOC);

            val.Start("JoinAll");
            FailureHandlingOptions failureHandlingOptions = val.GetFailureHandlingOptions();
            MyFailuresPreProcessor myFailuresPreProcessor = new MyFailuresPreProcessor();

            failureHandlingOptions.SetFailuresPreprocessor(myFailuresPreProcessor);
            val.SetFailureHandlingOptions(failureHandlingOptions);
            List <ElementId> list = new List <ElementId>();
            int num  = 0;
            int num2 = 0;

            foreach (Element item in this.FL)
            {
                if (!val.HasStarted())
                {
                    break;
                }
                num2++;
                this.Text = "HotGear Project Join All Process : " + num2.ToString() + "/" + this.PB;
                this.progressBar1.Value = num2;
                try
                {
                    GeometryElement val2 = item.get_Geometry(new Options());
                    Solid           val3 = null;
                    using (IEnumerator <GeometryObject> enumerator2 = val2.GetEnumerator())
                    {
                        if (enumerator2.MoveNext())
                        {
                            GeometryObject current2 = enumerator2.Current;
                            val3 = (current2 as Solid);
                            if (val3 != null)
                            {
                                list.Add(item.get_Id());
                            }
                        }
                    }
                    ElementIntersectsSolidFilter val4   = new ElementIntersectsSolidFilter(val3);
                    IList <Element>        values       = new FilteredElementCollector(this.DOC, (ICollection <ElementId>)list).WhereElementIsNotElementType().WherePasses(val4).ToElements();
                    Combinations <Element> combinations = new Combinations <Element>(values, 2, GenerateOption.WithoutRepetition);
                    foreach (List <Element> item2 in combinations)
                    {
                        if (!JoinGeometryUtils.AreElementsJoined(this.DOC, item2[0], item2[1]))
                        {
                            try
                            {
                                JoinGeometryUtils.JoinGeometry(this.DOC, item2[0], item2[1]);
                                num++;
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                catch
                {
                }
                base.Show();
                Application.DoEvents();
            }
            if (val.HasStarted())
            {
                this.I_trans.Commit();
                base.Close();
            }
        }
예제 #24
0
파일: Form1.cs 프로젝트: kaskanoidas/Boen
 private void KurtiVariantus(int SablonoNr, int parketoRusis)
 {
     combinationsList = new List<Combinations<string>> { };
     kiekiai = new List<int> { };
     NR = new List<IList<string>> { };
     for(int i = 0; i < sabl.SablonoElem[SablonoNr].JuostIlgis.Count; i++)
     {
         int k = 0;
         List<string> inputSet = new List<string> { };
         for (int j = 0; j < problem.ilgis.Count; j++)
         {
             if (problem.ilgis[j] == sabl.SablonoElem[SablonoNr].JuostIlgis[i])
             {
                 ++k;
                 inputSet.Add(problem.tipai[j]);
             }
         }
         int kiekis = sabl.SablonoElem[SablonoNr].Kiekis[i];
         Combinations<string> combinations = new Combinations<string>(inputSet, kiekis, GenerateOption.WithRepetition);
         combinationsList.Add(combinations);
         kiekiai.Add(kiekis);
         NR.Add(null);
     }
     rekursiveKurimas(0, SablonoNr, parketoRusis);
 }
예제 #25
0
 static void OtherTest()
 {
     Combinations<int> c3 = new Combinations<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 3);
     List<string> c3s = c3.Get(",");
 }
예제 #26
0
        public void Apriori(kValue kval)
        {
            Console.WriteLine("\nGenerating Frequent itemsets...");
            //_k = kval + 1;
            SetInitialCandidateAndFrequentSets();//initializes _candidateItemSets[0] manually and _frequentItemSets[0] based on condidates itemset support count
            for (int k = 1; k < kval; k++)
            {
                //_candidateItemSets[1] = GenerateKPlusOneCandidateItemsets(0);

                GenerateNextCandidateItemsets(k, AprioriMethod.Km1K1);//has to operate on kth frequent itemset _frequentItemSets[k]

                //_frequentItemSets[1] = GetFrquntCandidatesPrunedBySubsetSupport(1, kval);
                //Generate subsets of candidateItemSet and prune candidate itemsets containing subsets of length k that are infrequent       //GetFrquntCandidatesPrunedBySubsetSupport(k + 1, kval);    // has to operate on k+1th candidate itemset _candiateItemSets[k+1]
                Dictionary <ItemSet, Support> d = new Dictionary <string, float>();
                foreach (KeyValuePair <ItemSet, Support> kvp in _candidateItemSets[k - 1])
                {
                    bool retain = true;
                    Combinations <string> subsets = new Combinations <string>(kvp.Key.Split(','), k, GenerateOption.WithoutRepetition);
                    ItemSet[]             arr     = kvp.Key.Split(',');

                    if (subsets.Count > 0)
                    {
                        foreach (IList <ItemSet> subset in subsets)
                        {
                            float supportOfSubset = getMetricValue(string.Join(",", subset[0]), Metric.Support);
                            if (supportOfSubset < _minsup)
                            {
                                retain = false;
                                break;
                            }
                        }

                        if (retain)
                        {
                            d.Add(kvp.Key, kvp.Value);
                        }
                    }
                }
                _frequentItemSets.Add(k, d);


                List <ItemSet> toBeDeleted = new List <ItemSet>();
                foreach (KeyValuePair <ItemSet, Support> kvp in _frequentItemSets[k])
                {
                    float supportOfSuperSet = getMetricValue(kvp.Key, Metric.Support);
                    if (supportOfSuperSet < _minsup)
                    {
                        toBeDeleted.Add(kvp.Key);
                    }
                }

                //eliminate the candidates that are infrequent to leave only the frequent itemsets
                ///pruneFrequentCandidatesBySupport(k + 1);//has to operate on k+1th frequent itemset _frequentItemSets[k+1]
                //foreach(ItemSet itm in toBeDeleted)
                //{
                //    if (_frequentItemSets.ContainsKey(k))
                //    {
                //        _frequentItemSets[k].Remove(itm);
                //    }
                //}
            }
            for (int x = 0; x < _frequentItemSets.Count; x++)
            {
                foreach (KeyValuePair <string, float> kvpp in _frequentItemSets[x])
                {
                    if (getMetricValue(kvpp.Key, Metric.Support) < _minsup)
                    {
                        _frequentItemSets[x].Remove(kvpp.Key);
                        break;
                    }
                }
            }
            Console.WriteLine("\n...Finished generating frequent itemsets");
        }
예제 #27
0
파일: BLS.cs 프로젝트: MadMatt25/STP
        private void GetNeighbourSolutionWithSteinerNodeRemovalNeighbourhood(int breakout)
        {
            var initialSolution = CurrentSolution.Clone();
            foreach (var vertex in ProblemInstance.Vertices)
                if (!initialSolution.ContainsVertex(vertex))
                    initialSolution.AddVertex(vertex);

            int MAX_COMBINATIONS = (int) Math.Ceiling(Math.Log(ProblemInstance.NumberOfEdges)) * 4;
            var possibleVictims = CurrentSolution.Vertices.Where(x => CurrentSolution.GetDegree(x) > 0)
                                                          .Except(ProblemInstance.Required)
                                                          .OrderBy(x => x.AverageScore)
                                                          .Take(breakout * 2).ToList();
            int numberOfCombinations = Combinations<object>.NumberOfCombinations(possibleVictims.Count, breakout) > MAX_COMBINATIONS ? MAX_COMBINATIONS : Combinations<object>.NumberOfCombinations(possibleVictims.Count, breakout);
            var allCombinations = new Combinations<Vertex>(possibleVictims, breakout).GetRandomCombinations(numberOfCombinations);

            foreach (var removeSteiner in allCombinations)
            {
                var workingSolution = initialSolution.Clone();
                // Pick Steiner node
                var removeEdges = new HashSet<Edge>();
                foreach (var steiner in removeSteiner)
                {
                    foreach (var edge in workingSolution.GetEdgesForVertex(steiner))
                        removeEdges.Add(edge);
                }

                //Disconnect and reconnect
                foreach (var edge in removeEdges)
                    workingSolution.RemoveEdge(edge, false);
                //Prune current solution
                IEnumerable<Vertex> degreeOne;
                while ((degreeOne =
                        workingSolution.Vertices.Except(ProblemInstance.Terminals)
                            .Where(x => workingSolution.GetDegree(x) == 1)).Any())
                {
                    foreach (var degreeZeroSteiner in degreeOne.ToList())
                        foreach (var edge in workingSolution.GetEdgesForVertex(degreeZeroSteiner).ToList())
                            workingSolution.RemoveEdge(edge, false);
                }

                var previousNodes = workingSolution.Vertices.Where(x => workingSolution.GetDegree(x) > 0).ToList();

                ReconnectTerminals(workingSolution, ProblemInstance);

                if (workingSolution.TotalCost < CurrentSolution.TotalCost)
                {
                    //Console.Beep(2000, 150);
                    //Console.Beep(2100, 150);

                    foreach (var vertex in ProblemInstance.Vertices.Except(ProblemInstance.Terminals)
                                                                   .Intersect(workingSolution.Vertices))
                        vertex.IncreaseScore(3);

                    CurrentSolution = workingSolution.Clone();
                    return;
                }
                else
                {
                    foreach (var vertex in ProblemInstance.Vertices.Intersect(workingSolution.Vertices.Where(x => workingSolution.GetDegree(x) > 0).Except(previousNodes)))
                        vertex.DecreaseScore(1);
                }
            }
        }
예제 #28
0
        public void Run()
        {
            long percentComplete = 0;

            _exhuastiveCache = new Cache(10, 0.0);


            if ((_fitnessCrit == FitnessCriteria.R2) || (_fitnessCrit == FitnessCriteria.AdjustedR2))
            {
                _exhuastiveCache.Comparer = new DescendSort();
            }
            else if ((_fitnessCrit == FitnessCriteria.Sensitivity) || (_fitnessCrit == FitnessCriteria.Specificity) || (_fitnessCrit == FitnessCriteria.Accuracy))
            {
                _exhuastiveCache.Comparer = new DescendSort();
            }
            else
            {
                _exhuastiveCache.Comparer = new AscendSort();
            }

            IIndividual indiv = null;

            List <short> combList = new List <short>();
            short        tmp      = 0;;

            for (int i = 0; i < _numVars; i++)
            {
                //ListItem li = (ListItem)lbIndVariables.Items[i];
                tmp = (short)(i + 1);
                //tmp += Convert.ToInt16(li.ValueItem);
                combList.Add(tmp);
            }

            long totalComb     = 0;
            long totalComplete = 0;


            Combinations <short>         combinations = null;
            List <Combinations <short> > listAllComb  = new List <Combinations <short> >();

            for (short i = 1; i <= _maxVarsInModel; i++)
            {
                combinations = new Combinations <short>(combList.ToArray(), i, GenerateOption.WithoutRepetition);
                listAllComb.Add(combinations);
                totalComb += combinations.Count;
            }

            for (short i = 1; i <= _maxVarsInModel; i++)
            {
                if (Cancel)
                {
                    break;
                }

                //combinations = new Combinations<short>(combList.ToArray(), i, GenerateOption.WithoutRepetition);
                combinations = listAllComb[i - 1];
                foreach (IList <short> comb in combinations)
                {
                    if ((!Double.IsNaN(_decisionThreshold)) && (!Double.IsNaN(_mandateThreshold)) && (_maxVIF != Int32.MaxValue))
                    {
                        indiv = new MLRIndividual(i, i, _fitnessCrit, _maxVIF, _decisionThreshold, _mandateThreshold);
                    }
                    else if (_maxVIF != Int32.MaxValue)
                    {
                        indiv = new MLRIndividual(i, i, _fitnessCrit, _maxVIF);
                    }
                    else
                    {
                        indiv = new MLRIndividual(i, i, _fitnessCrit);
                    }

                    for (int j = 0; j < comb.Count; j++)
                    {
                        indiv.Chromosome[j] = comb[j];
                    }

                    if (Cancel)
                    {
                        break;
                    }

                    indiv.Evaluate();

                    if (indiv.IsViable())
                    {
                        //_exhuastiveCache.SortCache();
                        //_exhuastiveCache.ReplaceMinimum(indiv);
                        _exhuastiveCache.Add(indiv);
                    }
                    //else
                    //throw new Exception("Invalid individual.");



                    totalComplete++;

                    if ((totalComplete % 10) == 0)
                    {
                        percentComplete = totalComplete * 100 / totalComb;
                        ESProgress(percentComplete, _exhuastiveCache.MaximumFitness);
                        //VBLogger.getLogger().logEvent(percentComplete.ToString(), VBLogger.messageIntent.UserOnly, VBLogger.targetSStrip.ProgressBar);
                        //lblProgress.Text = "Progress: " + (Convert.ToDouble(totalComplete) / Convert.ToDouble(totalComb)) * 100;
                        //Console.WriteLine("Progress: " + (Convert.ToDouble(totalComplete) / Convert.ToDouble(totalComb)) * 100);
                        //lblProgress.Refresh();
                        //Application.DoEvents();
                    }
                }
            }
            _exhuastiveCache.Sort();

            //list = _exhuastiveCache.CacheList;


            //lbModels.Items.Clear();

            //UpdateFitnessListBox();
            ESComplete(this);
        }
예제 #29
0
파일: Program.cs 프로젝트: oldgittroy/base
        static void Main(string[] args)
        {
            // Permutations of an array.
            int[]  arr  = new int[] { 0, 3, 2, 1, 4, 9, 6, 7, 8, 5 };
            int[]  res  = new int[arr.Length];
            bool[] used = new bool[arr.Length];
            Permutations.PermuteArr(arr, res, used, 0, 0);
            //Permutations.PermuteArr(new List<int>(arr), 0);

            // Combinations of array.
            Console.Out.WriteLine("Now combinations");
            string        str      = "abcd";
            List <string> combntns = Combinations.CominateArr(str, str.Length);

            foreach (string st in combntns)
            {
                Console.Out.WriteLine(st);
            }

            GenericArray <int> .MergeSort(arr, 0, arr.Length - 1);

            int[,] mat = new int[, ] {
                { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 11 }, { 9, 20, 100 }
            };
            Tuple <int, int> searchIndex = ArraysStrings.ElementSearch2D(mat, 20, 0, mat.GetLength(0) - 1, 0, mat.GetLength(1) - 1);

            int[,] binary = new int[, ]
            {
                { 0, 1, 1, 0, 1 },
                { 1, 1, 0, 1, 0 },
                { 0, 1, 1, 1, 0 },
                { 1, 1, 1, 1, 0 },
                { 1, 1, 1, 1, 1 },
                { 0, 0, 0, 0, 0 }
            };

            int max1s = ArraysStrings.MaxSubmatrixOfOnes(binary);

            // Don't run this with large arrays.
            // Configurations.PrintConfigurations(arr, 0, res);

            StringBuilder paths = new StringBuilder();

            ArraysStrings.ListAllPaths(2, 2, paths);

            // Binary Search Trees.
            Node n1  = new Node(null, null, 1);
            Node n4  = new Node(null, null, 4);
            Node n3  = new Node(n1, n4, 3);
            Node n7  = new Node(null, null, 7);
            Node n12 = new Node(null, null, 12);
            Node n10 = new Node(n7, n12, 10);
            Node n5  = new Node(n3, n10, 5);

            // Arrays and strings.
            String testStr = "apple";

            double[,] input = new double[, ] {
                { 1, 9 }, { 15, 20 }
            };
            // ArraysStrings.CumulativeSum(input);

            double[,] optimals = ArraysStrings.OptimalPath(input);

            char[] inputChars = "apple".ToCharArray();
            ArraysStrings.removeDuplicates(inputChars);

            // Data structures.
            Stack <Node>                   stk   = new Stack <Node>();
            Queue <Node>                   qu    = new Queue <Node>();
            Dictionary <string, int>       dict  = new Dictionary <string, int>();
            SortedDictionary <string, int> sdict = new SortedDictionary <string, int>();
            List <int> lst = new List <int>();

            Console.Read();
        }
예제 #30
0
        private List<CodePattern> BuildPatternList(Guess guess, int lowerIndex)
        {
            var patterns = new List<CodePattern>();
            var basePattern = new List<int?>() { guess[0], guess[1], guess[2], guess[3] };
            var positions = Enumerable.Range(0, guess.Value.Count).ToList();

            var variations = new Combinations<int>(positions, lowerIndex, GenerateOption.WithoutRepetition);

            foreach (var variation in variations)
            {
                var basePatternCopy = new List<int?>(basePattern);

                for (var i = 0; i < basePatternCopy.Count; i++)
                {
                    if (variation.Contains(i) == false)
                    {
                        basePatternCopy[i] = null;
                    }
                }

                patterns.Add(new CodePattern(basePatternCopy));
            }

            return patterns;
        }
예제 #31
0
        //метод по определению комбинации и инициализирует
        //промежуточные переменные, присваемые игроку
        private void defineGeneral(int[] countArr, out int H, out int L, out Combinations comb)
        {
            H    = L = 0;
            comb = Combinations.None;

            int  pairH     = 0;
            bool set       = false;
            bool fullhouse = false;
            bool care      = false;
            bool pair      = false;

            //в цикле анализируется по кол-ву совпадений
            //каждая позиция для определения комбинации
            for (int i = 0; i < countArr.Length; i++)
            {
                //определение комбинации "пара" или " две пары"
                if (countArr[i] == 2)
                {
                    pairH = (arrOftc[i] > pairH) ? arrOftc[i] : pairH;
                    pair  = true;
                    if (countArr[i] == 2 && arrOftc[i] > L &&
                        !set && !fullhouse && !care)
                    {
                        L = (arrOftc[i] > L && arrOftc[i] > H) ? H : arrOftc[i];
                        if (arrOftc[i] > H && !fullhouse && !care && !set)
                        {
                            H = arrOftc[i];
                        }
                        comb = (L == H || L == 0) ? Combinations.Pair : Combinations.TwinPair;
                    }
                }

                //определие комбинации "Сет"
                if (countArr[i] == 3 && L == 0)
                {
                    set = true;
                    H   = arrOftc[i];
                    if (arrOftc[0] != arrOftc[1])
                    {
                        L = (arrOftc[0] != arrOftc[i] &&
                             arrOftc[1] != arrOftc[i] &&
                             arrOftc[0] > arrOftc[1]) ? arrOftc[0] : arrOftc[1];
                    }
                    comb = Combinations.Set;
                }

                //определение комбинации "ФулХаус"
                if (set && pair)
                {
                    fullhouse = true;
                    set       = false;
                    L         = pairH;
                    comb      = Combinations.Fullhouse;
                }

                //определение комбинации "Карэ"
                if (countArr[i] == 4)
                {
                    care = true;
                    H    = arrOftc[i];
                    L    = (arrOftc[0] != arrOftc[i] &&
                            arrOftc[1] != arrOftc[i] &&
                            arrOftc[0] > arrOftc[1]) ? arrOftc[0] : arrOftc[1];
                    comb = Combinations.Care;
                }
            }
        }
예제 #32
0
        public void Run()
        {
            long percentComplete = 0;
            _exhuastiveCache = new Cache(10, 0.0);

            if ((_fitnessCrit == FitnessCriteria.R2) || (_fitnessCrit == FitnessCriteria.AdjustedR2))
            {
                _exhuastiveCache.Comparer = new DescendSort();
            }
            else if ((_fitnessCrit == FitnessCriteria.Sensitivity) || (_fitnessCrit == FitnessCriteria.Specificity) || (_fitnessCrit == FitnessCriteria.Accuracy))
            {
                _exhuastiveCache.Comparer = new DescendSort();
            }
            else
            {
                _exhuastiveCache.Comparer = new AscendSort();
            }

            IIndividual indiv = null;

            List<short> combList = new List<short>();
            short tmp = 0; ;
            for (int i = 0; i < _numVars; i++)
            {
                //ListItem li = (ListItem)lbIndVariables.Items[i];
                tmp = (short)(i + 1);
                //tmp += Convert.ToInt16(li.ValueItem);
                combList.Add(tmp);
            }

            long totalComb = 0;
            long totalComplete = 0;

            Combinations<short> combinations = null;
            List<Combinations<short>> listAllComb = new List<Combinations<short>>();
            for (short i = 1; i <= _maxVarsInModel; i++)
            {
                combinations = new Combinations<short>(combList.ToArray(), i, GenerateOption.WithoutRepetition);
                listAllComb.Add(combinations);
                totalComb += combinations.Count;
            }

            for (short i = 1; i <= _maxVarsInModel; i++)
            {
                if (Cancel)
                    break;

                //combinations = new Combinations<short>(combList.ToArray(), i, GenerateOption.WithoutRepetition);
                combinations = listAllComb[i - 1];
                foreach (IList<short> comb in combinations)
                {

                    if ((!Double.IsNaN(_decisionThreshold)) && (!Double.IsNaN(_mandateThreshold)) && (_maxVIF != Int32.MaxValue))
                        indiv = new MLRIndividual(i, i, _fitnessCrit, _maxVIF, _decisionThreshold, _mandateThreshold);
                    else if (_maxVIF != Int32.MaxValue)
                        indiv = new MLRIndividual(i, i, _fitnessCrit, _maxVIF);
                    else
                        indiv = new MLRIndividual(i, i, _fitnessCrit);

                    for (int j = 0; j < comb.Count; j++)
                        indiv.Chromosome[j] = comb[j];

                    if (Cancel)
                        break;

                    indiv.Evaluate();

                    if (indiv.IsViable())
                    {
                        //_exhuastiveCache.SortCache();
                        //_exhuastiveCache.ReplaceMinimum(indiv);
                        _exhuastiveCache.Add(indiv);
                    }
                    //else
                        //throw new Exception("Invalid individual.");

                    totalComplete++;

                    if ((totalComplete % 10) == 0)
                    {
                        percentComplete = totalComplete * 100 / totalComb;
                        ESProgress(percentComplete, _exhuastiveCache.MaximumFitness);
                        //VBLogger.getLogger().logEvent(percentComplete.ToString(), VBLogger.messageIntent.UserOnly, VBLogger.targetSStrip.ProgressBar);
                        //lblProgress.Text = "Progress: " + (Convert.ToDouble(totalComplete) / Convert.ToDouble(totalComb)) * 100;
                        //Console.WriteLine("Progress: " + (Convert.ToDouble(totalComplete) / Convert.ToDouble(totalComb)) * 100);
                        //lblProgress.Refresh();
                        //Application.DoEvents();
                    }

                }
            }
            _exhuastiveCache.Sort();

            //list = _exhuastiveCache.CacheList;

            //lbModels.Items.Clear();

            //UpdateFitnessListBox();
            ESComplete(this);
        }
예제 #33
0
        protected override void CreateChildControls()
        {
            try
            {
                //emit claims as JSON
                Dictionary <string, string> dicClaimsJson = GetClaimsForJSON();
                string claimsJson = JsonConvert.SerializeObject(dicClaimsJson);
#if DEBUG
                this.Controls.Add(new LiteralControl("<div>Claims JSON:" + claimsJson + "</div>"));
#endif
                this.Controls.Add(new LiteralControl("<script> var claimsJSONMap = " + claimsJson + " </script>"));

                //Updte permissions and profile if claims changed.
#if DEBUG
                this.Controls.Add(new LiteralControl("<div>Current Claims:</div><ul>"));
#endif
                Dictionary <string, string> claims = GetClaimsForUser(false);
                if (_claimsCookie != null)
                {
                    claims = CompareChanges(claims, JsonConvert.DeserializeObject <Dictionary <string, string> >(_claimsCookie.Value));
                }
                //TODO: Re-enable

                /*if (claims.Count < 1) //ignore users with no claims, and windows users
                 *  return;*/
                currentProfile = GetCurrentProfile();
                List <string> values  = new List <string>();
                string        claimUP = "";
                foreach (string k in claims.Keys)
                {
#if DEBUG
                    this.Controls.Add(new LiteralControl("<li>" + k + " - " + claims[k] + "</li>"));
#endif
                    claimUP += k + "-" + claims[k] + "|";
                    values.Add(claims[k]);
                }

                if (ClaimsChanged(claimUP))
                {
#if DEBUG
                    this.Controls.Add(new LiteralControl("</ul><div>Claim Permutations</div><ul>"));
#endif
                    List <string> allcombos = new List <string>();
                    for (int i = 2; i <= values.Count - 1; i++)
                    {
                        var combis = new Combinations <string>(values, i, GenerateOption.WithoutRepetition);
                        allcombos.AddRange(combis.Select(c => string.Join(" ", c)));
                    }
#if DEBUG
                    foreach (string c in allcombos)
                    {
                        this.Controls.Add(new LiteralControl("<li>" + c + "</li>"));
                    }
                    this.Controls.Add(new LiteralControl("</ul>"));
#endif

                    //verify permissions
                    VerifyPermissions(allcombos);
                    UpdateProfile(claimUP);
                }
            }
            catch (Exception ex)
            {
                this.Controls.Add(new LiteralControl("<div class='error'><div>Error in mapping incoming claims to sharepoint groups</div><div class='msg'>" + ex.Message + "</div><div class='trace' style='display:none'>" + ex.StackTrace + "</div><div class='innerException' style='display:none'>" + ex.InnerException + "</div></div>"));
            }
        }
예제 #34
0
        private List<IList<DigitWithPosition>> CreateCowCombinations(Guess guess, List<DigitWithPosition> potentialCows)
        {
            var cows = new List<DigitWithPosition>();

            foreach (var potentialCow in potentialCows)
            {
                var otherPositions = potentialCows
                    .Where(c => c.Digit != potentialCow.Digit)
                    .Select(c => c.Position);

                cows.AddRange(otherPositions.Select(p => new DigitWithPosition(potentialCow.Digit, p)));
            }

            var cowCombinations =new Combinations<DigitWithPosition>(cows, guess.Cows, GenerateOption.WithoutRepetition).ToList();
            StripOutInvalidCowCombinations(cowCombinations);
            return cowCombinations;
        }
예제 #35
0
 public void Works_with_no_items_and_k_0()
 {
     var variations = new Combinations<string>(Enumerable.Empty<string>(), 0);
     GenerateOutput(variations);
     AreEqual(GetExpectedTestOutput(), GetActualTestOutput());
 }
예제 #36
0
        public override Task <Card> GetCountCard(List <Card> playedCards, List <Card> uncountedCards, int currentCount)
        {
            var  maxScore = -1;
            Card maxCard  = null;
            var  score    = 0;


            //
            // if we have only 1 card, play it if we legally can
            //  NOTE: we assume that the Player correctly returns a legal card!
            //
            if (uncountedCards.Count == 1)
            {
                if (uncountedCards[0].Value + currentCount <= 31)
                {
                    return(Task.FromResult(uncountedCards[0]));
                }
                else
                {
                    return(Task.FromResult <Card>(null));
                }
            }

            //
            //  see which card we can play that gives us the most points
            foreach (var c in uncountedCards)
            {
                score = CardScoring.ScoreCountingCardsPlayed(playedCards, c, currentCount, out var scoreList);
                if (score > maxScore)
                {
                    maxScore = score;
                    maxCard  = c;
                }
            }

            if (maxScore == -1)
            {
                return(Task.FromResult <Card>(null));
            }
            ;  // we have no valid card to play

            if (maxScore > 0)
            {
                return(Task.FromResult(maxCard));
            }

            if (maxScore == 0) // there isn't a card for us to play that generates points
            {
                //
                //  play a card that we have a pair so we can get 3 of a kind - as long as it isn't a 5 and the 3 of a kind makes > 31
                //
                //  this optimization changes the average count score from 2.59948 to 2.66909 over 100,000 games
                //
                for (var i = 0; i < uncountedCards.Count - 1; i++)
                {
                    //  dont' do it if it will force us over 31
                    if (uncountedCards[i].Rank * 3 + currentCount > 31)
                    {
                        continue;
                    }

                    if (uncountedCards[i].Rank == uncountedCards[i + 1].Rank)
                    {
                        if (uncountedCards[i].Rank != 5)
                        {
                            return(Task.FromResult(uncountedCards[i]));
                        }
                    }
                }

                //
                //  make the right choice if assuming they'll play a 10
                //
                //  this optimization changes the average count score from 2.64235 to 2.67764 over 100,000 games
                //
                var combinations = new Combinations <Card>(uncountedCards, 2); // at most 6 of these: 4 choose 2
                foreach (List <Card> cards in combinations)
                {
                    var sum = cards[0].Value + cards[1].Value;
                    if (sum + currentCount == 5) // i'll 15 them if they play a 10
                    {
                        return(Task.FromResult(cards[1]));
                    }

                    if (sum + currentCount == 21) // i'll 31 them if they play a 10
                    {
                        return(Task.FromResult(cards[1]));
                    }
                }

                // tried returning the smallest legal card -- no difference
                // tried returning the highest legal card -- no difference
            }

            // tried to generate a random card if currentCount == 0 -- no difference


            //
            //  this one is important -- it basically says "if you can't score any points, induce a 3 of a kind, or try to create a run play whatever card we ened up with.
            //  UNLESS IT IS A FIVE!...then pick a different one.  over the course of 100,000 games, this is the difference between 2.61423 and 2.71498 ave counting points
            //  turns out that if we don't do this, then both players get ~2.65 points / counting session - e.g. if one is not worried about dropping 5's and the other is, it
            //  adds about .1/count and if both are being silly and dropping 5's then both get about .04 ave point boost.  still a good optimization when playing humans.

            if (maxCard.Rank == 5)
            {
                foreach (var c in uncountedCards)
                {
                    if (c.Rank != 5 && c.Value + currentCount <= 31)
                    {
                        maxCard = c;
                        break;
                    }
                }
            }

            //
            //   don't play a card that adds up to 5 because there are so many 10's

            if (maxCard.Value + currentCount != 5)
            {
                return(Task.FromResult(maxCard));
            }


            foreach (var c in uncountedCards)
            {
                //
                //  also don't play a card that if they play the same card will give them
                //  both a pair and a 15
                if (c.Value + currentCount == 5 || c.Value * 2 + currentCount == 15)
                {
                }
                else
                {
                    maxCard = c;
                    break;
                }
            }


            return(Task.FromResult(maxCard));
        }
예제 #37
0
 public void Works_with_3_items_and_k_0()
 {
     var variations = new Combinations<string>(new[] { "a", "b", "c" }, 0);
     GenerateOutput(variations);
     AreEqual(GetExpectedTestOutput(), GetActualTestOutput());
 }