Beispiel #1
0
        static void Main()
        {
            List<string> names = new List<string>() 
            { "Presho", "Gosho", "Stoian", "Minka", "Ceca", "Meca", "Chicho", "Dicho" };

            int combinationBase = 3;

            CombinationGenerator<string> combinationGenerator = new CombinationGenerator<string>(combinationBase,names);

            List<string[]> result = combinationGenerator.ResultCombinations;

            foreach (var combination in result)
            {
                for (int i = 0; i < combinationBase; i++)
                {
                    if (i < combinationBase - 1)
                    {
                        Console.Write("{0,20}, ", combination[i]);
                    }
                    else
                    {
                        Console.WriteLine("{0,20}", combination[i]); 
                    }
                }                
            }
        }
        public void GenerateRightCombinationsForNEqualsThree()
        {
            CombinationGenerator generator = new CombinationGenerator();
            var result = generator.Generate(25, 3);

            Assert.Equal(25, result.Count);
            Assert.Equal(new int[] { }, result[0]);
            Assert.Equal(new[] { 1 }, result[1]);
            Assert.Equal(new[] { 2 }, result[2]);
            Assert.Equal(new[] { 3 }, result[3]);
            Assert.Equal(new[] { 1, 1 }, result[4]);
            Assert.Equal(new[] { 1, 2 }, result[5]);
            Assert.Equal(new[] { 1, 3 }, result[6]);
            Assert.Equal(new[] { 2, 2 }, result[7]);
            Assert.Equal(new[] { 2, 3 }, result[8]);
            Assert.Equal(new[] { 3, 3 }, result[9]);
            Assert.Equal(new[] { 1, 1, 1 }, result[10]);
            Assert.Equal(new[] { 1, 1, 2 }, result[11]);
            Assert.Equal(new[] { 1, 1, 3 }, result[12]);
            Assert.Equal(new[] { 1, 2, 2 }, result[13]);
            Assert.Equal(new[] { 1, 2, 3 }, result[14]);
            Assert.Equal(new[] { 1, 3, 3 }, result[15]);
            Assert.Equal(new[] { 2, 2, 2 }, result[16]);
            Assert.Equal(new[] { 2, 2, 3 }, result[17]);
            Assert.Equal(new[] { 2, 3, 3 }, result[18]);
            Assert.Equal(new[] { 3, 3, 3 }, result[19]);
        }
        public void Generator_NoCombinationPossible_ReturnsNull()
        {
            var generator = new CombinationGenerator(StandardKeypad);
            var test      = generator.Generate("0000000000").FirstOrDefault();

            Assert.IsNull(test);
        }
Beispiel #4
0
        public IList <string> LetterCasePermutation(string S)
        {
            List <string> list = new List <string>();

            CombinationGenerator.Generate(
                S.Length,
                ptr => IsLetter(S[ptr]) ? 2 : 1,
                (ptr, index) => index,
                flags => {
                StringBuilder sb = new StringBuilder(S.Length);

                for (int i = 0; i < flags.Length; i++)
                {
                    char c = S[i];

                    if (IsLower(c))
                    {
                        sb.Append(flags[i] == 0 ? c : ToUpper(c));
                    }
                    else if (IsUpper(c))
                    {
                        sb.Append(flags[i] == 0 ? ToLower(c) : c);
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                list.Add(sb.ToString());
            }
                );

            return(list);
        }
        public void GenerateReturnsRightNumberOfCombinations()
        {
            CombinationGenerator generator = new CombinationGenerator();
            var result = generator.Generate(112, 2);

            Assert.Equal(112, result.Count);
        }
        public void Generator_InvalidPhoneNumber_ReturnsNull()
        {
            var generator = new CombinationGenerator(StandardKeypad);
            var test      = generator.Generate("(ABC)").FirstOrDefault();

            Assert.IsNull(test);
        }
        public void Generator_ThreadSafe_TaskReaders()
        {
            var generator   = new CombinationGenerator(StandardKeypad);
            var threadCount = 1000;
            var batchSize   = 100;

            var tasks = Enumerable.Range(1, threadCount)
                        .Select(_ =>
                                Task.Factory.StartNew(() => generator.Generate(TEST_PHONE_NUMBER).Take(batchSize).ToList())
                                )
                        .ToArray();

            Task.WaitAll(tasks);


            var sequentialGenerator = new CombinationGenerator(StandardKeypad);
            var sequence            = sequentialGenerator.Generate(TEST_PHONE_NUMBER).Take(threadCount * batchSize).ToList();

            for (var i = 0; i < batchSize; i++)
            {
                foreach (var task in tasks)
                {
                    Assert.AreEqual(sequence[i], task.Result[i]);
                }
            }
        }
        public void testGeneration()
        {
            IList <IList <string> > generatedStrings = new List <IList <string> >();

            CombinationGenerator.generate(
                new List <string>()
            {
                "a", "b"
            },
                new List <string>(),
                generatedStrings,
                2
                );

            Assert.AreEqual(4, generatedStrings.Count);

            foreach (var generatedString in generatedStrings)
            {
                Assert.AreEqual(2, generatedString.Count);
            }

            Assert.AreEqual(new List <string> {
                "a", "a"
            }, generatedStrings[0]);
            Assert.AreEqual(new List <string> {
                "a", "b"
            }, generatedStrings[1]);
            Assert.AreEqual(new List <string> {
                "b", "a"
            }, generatedStrings[2]);
            Assert.AreEqual(new List <string> {
                "b", "b"
            }, generatedStrings[3]);
        }
Beispiel #9
0
            /// <summary>
            /// Generate all possible permutations of length nChosen.
            /// </summary>
            /// <param name="nChosen">nChosen must be ≥ 0 and ≤ data.Length</param>
            public List <double[]> GetPermutations(int nChosen)
            {
                if (nChosen < 0)
                {
                    throw new ArgumentException("nChosen cannot be less than zero. nChosen must be ≥ 0 and ≤ data.Length");
                }
                if (nChosen > _data.Length)
                {
                    throw new ArgumentException("nChosen cannot be less than zero. nChosen must be ≥ 0 and ≤ data.Length");
                }
                if (nChosen == 0)
                {
                    return new List <double[]> {
                               new double[0]
                    }
                }
                ;

                if (nChosen == _data.Length)
                {
                    return(GetPermut(_data));
                }

                CombinationGenerator cg      = new CombinationGenerator(_data);
                List <double[]>      combins = cg.Combinations(nChosen);
                List <double[]>      permuts = new List <double[]>();

                foreach (double[] da in combins)
                {
                    permuts.AddRange(GetPermut(da));
                }
                return(permuts);
            }
Beispiel #10
0
        public void ExtractCombinationsOfThreeElementsFromFive()
        {
            var generator = new CombinationGenerator();
            var combinations = generator.GetCombinations(new List<string> { "A", "B", "C", "D", "E" }, 3).ToList();

            Assert.AreEqual(10, combinations.Count(), "Ten ways to do this");

            // ABC
            // ABD
            // ABE
            // ACD
            // ACE
            // ADE
            // BCD
            // BCE
            // BDE
            // CDE

            var list = combinations.Select(combination => string.Concat(combination)).ToList();

            Assert.IsTrue(list.Contains("ABC"));
            Assert.IsTrue(list.Contains("ABD"));
            Assert.IsTrue(list.Contains("ABE"));
            Assert.IsTrue(list.Contains("ACD"));
            Assert.IsTrue(list.Contains("ACE"));
            Assert.IsTrue(list.Contains("ADE"));
            Assert.IsTrue(list.Contains("BCD"));
            Assert.IsTrue(list.Contains("BCE"));
            Assert.IsTrue(list.Contains("BDE"));
            Assert.IsTrue(list.Contains("CDE"));
        }
        public void Generator_IsIEnumerable()
        {
            var generator    = new CombinationGenerator(StandardKeypad);
            var combinations = generator.Generate(TEST_PHONE_NUMBER).Take(10).ToList();

            Assert.AreEqual(10, combinations.Count());
            combinations.ForEach(Console.WriteLine);
        }
        public void Generator_SecondToLastSymbolChanges_OK()
        {
            var phoneNumber = "3015559860";
            var generator   = new CombinationGenerator(StandardKeypad);
            var nextNumbers = generator.Generate(phoneNumber).Take(2).ToArray();

            Assert.AreEqual(nextNumbers[0], "30155598M0");
            Assert.AreEqual(nextNumbers[1], "30155598N0");
        }
        public void Generator_LastSymbolChanges_OK()
        {
            var phoneNumber  = "3015559876";
            var generator    = new CombinationGenerator(StandardKeypad);
            var combinations = generator.Generate(phoneNumber).Take(3).ToArray();

            Assert.AreEqual(combinations[0], "301555987M");
            Assert.AreEqual(combinations[1], "301555987N");
            Assert.AreEqual(combinations[2], "301555987O");
        }
Beispiel #14
0
        public void TestCombinationGenerator()
        {
            // Item1 is the input string whose characters will be used to
            // generate combinations, item2 is the desired combination size
            // and item3 is the array of combinations expected to be generated.
            Tuple <string, uint, string[]>[] test_vectors =
            {
                new Tuple <string,                                                                          uint,   string[]>(
                    "ABC",
                    0,
                    new string[] { }),

                new Tuple <string,                                                                          uint,   string[]>(
                    "ABCDE",
                    6,
                    new string[] { }),

                new Tuple <string,                                                                          uint,   string[]>(
                    "ABCDE",
                    3,
                    new string[] { "ABC",                                                                   "ABD",  "ABE",    "ACD",  "ACE", "ADE", "BCD", "BCE", "BDE", "CDE" }),

                new Tuple <string,                                                                          uint,   string[]>(
                    "ABCDE",
                    1,
                    new string[] { "A",                                                                     "B",    "C",      "D",    "E" }),

                new Tuple <string,                                                                          uint,   string[]>(
                    "ABCDE",
                    2,
                    new string[] { "AB",                                                                    "AC",   "AD",     "AE",   "BC",  "BD",  "BE",  "CD",  "CE",  "DE"  }),

                new Tuple <string,                                                                          uint,   string[]>(
                    "ABCDE",
                    4,
                    new string[] { "ABCD",                                                                  "ABCE", "ABDE",   "ACDE", "BCDE" })
            };

            foreach (var test_vector in test_vectors)
            {
                List <string> combinations = new List <string>();
                CombinationGenerator.Run(test_vector.Item1, test_vector.Item2, combinations);

                Assert.AreEqual(test_vector.Item3.Length, combinations.Count);

                Array.Sort(test_vector.Item3);
                combinations.Sort();

                int i = 0;
                foreach (var combination in test_vector.Item3)
                {
                    Assert.AreEqual(combination, combinations[i++]);
                }
            }
        }
        public void Generator_LastTwoSymbolsChange_OK()
        {
            var phoneNumber  = "301555987O";
            var generator    = new CombinationGenerator(StandardKeypad);
            var combinations = generator.Generate(phoneNumber).Take(5).ToArray();

            Assert.AreEqual(combinations[0], "30155598P6");
            Assert.AreEqual(combinations[1], "30155598PM");
            Assert.AreEqual(combinations[2], "30155598PN");
            Assert.AreEqual(combinations[3], "30155598PO");
        }
        public void Generator_AllCombinations_Verified()
        {
            var phoneNumber = "2";
            var generator   = new CombinationGenerator(StandardKeypad);
            var nextNumbers = generator.Generate(phoneNumber).Take(1000).ToArray();

            Assert.AreEqual(3, nextNumbers.Length);
            Assert.AreEqual("A", nextNumbers[0]);
            Assert.AreEqual("B", nextNumbers[1]);
            Assert.AreEqual("C", nextNumbers[2]);
        }
Beispiel #17
0
        public string NextClosestTime(string time)
        {
            int hh = Int32.Parse(time.Substring(0, 1));
            int hl = Int32.Parse(time.Substring(1, 1));
            int mh = Int32.Parse(time.Substring(3, 1));
            int ml = Int32.Parse(time.Substring(4, 1));

            int i_time = hh * 1000 + hl * 100 + mh * 10 + ml;

            HashSet <int> digits_hs = new HashSet <int>();

            digits_hs.Add(hh);
            digits_hs.Add(hl);
            digits_hs.Add(mh);
            digits_hs.Add(ml);

            int[] digits = digits_hs.ToArray();

            int min_time = i_time + 10000;

            CombinationGenerator.Generate(4, digits, a => {
                if (a[0] > 2)
                {
                    return;
                }
                if (a[2] > 5)
                {
                    return;
                }

                int v_h = a[0] * 10 + a[1];
                int v_m = a[2] * 10 + a[3];
                if (v_h <= 23 && v_m <= 59)
                {
                    // Console.WriteLine("{0}{1}:{2}{3}", a[0], a[1], a[2], a[3]);

                    int v_time = v_h * 100 + v_m;
                    if (v_time != i_time)
                    {
                        if (v_time < i_time)
                        {
                            v_time += 10000;
                        }
                        min_time = Math.Min(v_time, min_time);
                    }
                }
            });

            min_time %= 10000;

            return(String.Format("{0:00}:{1:00}", min_time / 100, min_time % 100));
        }
Beispiel #18
0
        public IList <string> AddOperators(string num, int target)
        {
            if (num.Length == 0)
            {
                return(Array.Empty <string>());
            }
            else if (num.Length == 1)
            {
                int n = Int32.Parse(num);
                if (n == target)
                {
                    return(new[] { num });
                }
                else
                {
                    return(Array.Empty <string>());
                }
            }

            Func <int, int, long?>[] op_func =
            {
                (a, b) => a + b,
                (a, b) => a - b,
                (a, b) => a * b,
                (a, b) => a > 0 ? (int?)a * 10 + b : null
            };

            string[] op_char = { "+", "-", "*", "" };

            int[] nums = new int[num.Length];
            for (int i = 0; i < num.Length; i++)
            {
                nums[i] = Int32.Parse(num.Substring(i, 1));
            }

            List <string> list = new List <string>();

            CombinationGenerator.Generate(nums.Length - 1, new[] { 10, 11, 22, 33 }, ops => {
                Stack <int> op_stack = new Stack <int>();
                Queue <int> n_output = new Queue <int>();

                for (int i = 0; i < ops.Length; i++)
                {
                    n_output.Enqueue(nums[i]);

                    while (op_stack.TryPeek(out int op) && op / 10 >= ops[i] / 10)
                    {
                        n_output.Enqueue(op_stack.Pop());
                    }

                    op_stack.Push(ops[i]);
                }
Beispiel #19
0
        /// <summary>
        /// This function will calculate the discrete Attribute's Entropy value
        /// </summary>
        /// <param name="attributes">an array of discrete attribute value</param>
        /// <param name="classNumbers">a list of class numbers</param>
        /// <returns>the entropy value</returns>
        public double CalcAttributeGini(string[] attributes, byte[] classNumbers)
        {
            IList <string> uniqValues   = new List <string>();
            IList <int>    samplesCount = new List <int>();

            GetUniqValuesSamples <string>(attributes, out uniqValues, out samplesCount);
            double AttributeEntro = 1.0;
            long   total          = classNumbers.Length;

            CombinationGenerator <string> cg = new CombinationGenerator <string>();
            IEnumerable <List <string> >  potentialCombinations = cg.ProduceWithoutRecursion(uniqValues as List <string>);

            foreach (List <string> combination in potentialCombinations)
            {
                if (combination.Count != 0 && combination.Count == uniqValues.Count)
                {
                    IList <byte> subsetClass = new List <byte>();
                    //in
                    splitVectorByContainage(attributes, classNumbers, combination, true, out subsetClass);
                    byte[]       inClassArray     = convertList2Array(subsetClass);
                    IList <byte> uniqClass        = new List <byte>();
                    IList <int>  uniqClassSamples = new List <int>();
                    GetUniqValuesSamples(inClassArray, out uniqClass, out uniqClassSamples);
                    double inEntropy = getGiniValuefromProbability(uniqClassSamples);
                    long   subTotal  = 0;
                    foreach (int value in uniqClassSamples)
                    {
                        subTotal += value;
                    }
                    inEntropy = inEntropy * ((subTotal * 1.0) / total);
                    //Not in
                    splitVectorByContainage(attributes, classNumbers, combination, true, out subsetClass);
                    byte[] notInClassArray = convertList2Array(subsetClass);
                    uniqClass        = new List <byte>();
                    uniqClassSamples = new List <int>();
                    GetUniqValuesSamples(inClassArray, out uniqClass, out uniqClassSamples);
                    double notInEntropy = getGiniValuefromProbability(uniqClassSamples);
                    subTotal = 0;
                    foreach (int value in uniqClassSamples)
                    {
                        subTotal += value;
                    }
                    notInEntropy = notInEntropy * ((subTotal * 1.0) / total);
                    if (inEntropy + notInEntropy < AttributeEntro)
                    {
                        AttributeEntro = inEntropy + notInEntropy;
                    }
                }
            }
            return(AttributeEntro);
        }
        public void Generator_TotalItemCount_CorrectWithOneDigit()
        {
            var generator = new CombinationGenerator(StandardKeypad);

            Assert.AreEqual(0, generator.TotalItemCount("0"));
            Assert.AreEqual(0, generator.TotalItemCount("1"));
            Assert.AreEqual(3, generator.TotalItemCount("2"));
            Assert.AreEqual(3, generator.TotalItemCount("3"));
            Assert.AreEqual(3, generator.TotalItemCount("4"));
            Assert.AreEqual(3, generator.TotalItemCount("5"));
            Assert.AreEqual(3, generator.TotalItemCount("6"));
            Assert.AreEqual(4, generator.TotalItemCount("7"));
            Assert.AreEqual(3, generator.TotalItemCount("8"));
            Assert.AreEqual(4, generator.TotalItemCount("9"));
        }
        public void Generator_TotalItemCount_CorrectWithMoreDigits()
        {
            var generator = new CombinationGenerator(StandardKeypad);

            Assert.AreEqual(0, generator.TotalItemCount("000"));
            Assert.AreEqual(0, generator.TotalItemCount("101"));

            Assert.AreEqual(3, generator.TotalItemCount("200"));
            Assert.AreEqual(3, generator.TotalItemCount("113"));

            Assert.AreEqual(3 * 3 * 3, generator.TotalItemCount("222"));

            Assert.AreEqual(Math.Pow(3, 10), generator.TotalItemCount("5552224444"));
            Assert.AreEqual(Math.Pow(4, 10), generator.TotalItemCount("7779997777"));
        }
    void Summon()
    {
        // New wave
        if (EnemiesForCurrentWave.Count <= 0 && NbrEnemiesOnScreen == 0)
        {
            if (WaveLeft.Count > 0)
            {
                TimeLeft = 5;
                EnemiesForCurrentWave = WaveLeft [0];
                WaveLeft.RemoveAt(0);
                StartCoroutine("SummonLater", TimeLeft);
                return;
            }
        }

        // The wave continue
        if (EnemiesForCurrentWave.Count >= 1)
        {
            Transform BasicEnemy  = EnemiesForCurrentWave [0].transform;
            int       randomIndex = Random.Range(0, SpawnerPositionList.Count - 1);
            //Debug.Log ("count : " + SpawnerPositionList.Count);

            Vector3 pos = SpawnerPositionList[randomIndex];

            float ysize   = BasicEnemy.GetComponent <BoxCollider> ().size.y;
            float ycenter = BasicEnemy.GetComponent <BoxCollider> ().center.y;
            float yscale  = BasicEnemy.GetComponent <Transform>().localScale.y;
            pos.y -= (ysize * (yscale / 2)) + (ycenter * yscale);

            Debug.Log("test : " + BasicEnemy.GetComponent <BoxCollider> ().center.y);

            //pos.y -= BasicEnemy.GetComponent<BoxCollider>().size.y * BasicEnemy.GetComponent<Transform>().localScale.y / 2;
            Tutorial_Ennemy      enemy = Instantiate(BasicEnemy.gameObject, pos, Quaternion.identity).GetComponent <Tutorial_Ennemy>();
            CombinationGenerator c     = new CombinationGenerator();
            c.FixedSize       = enemy.Combination.Count;
            enemy.Combination = c.GetListButton();
            enemy.Setup();
            NbrEnemiesOnScreen++;
            Tutorial_GameManager.instance.EnemiesOnScreen.Add(enemy.gameObject);

            if (EnemiesForCurrentWave.Count >= 2)
            {
                TimeLeft = EnemiesForCurrentWave [1].SpawnCooldown;
            }

            EnemiesForCurrentWave.RemoveAt(0);
        }
    }
Beispiel #23
0
        public string[] Expand(string s)
        {
            IList <IList <char> > map = new List <IList <char> >();

            List <char> chars = null;

            foreach (char c in s)
            {
                if (c == '{')
                {
                    chars = new List <char>();
                }
                else if (c == '}')
                {
                    map.Add(chars.ToArray());
                    chars = null;
                }
                else if (c == ',')
                {
                    // NOP
                }
                else
                {
                    if (chars != null)
                    {
                        chars.Add(c);
                    }
                    else
                    {
                        map.Add(new[] { c });
                    }
                }
            }

            List <string> list = new List <string>();

            CombinationGenerator.Generate(
                map.Count,
                map,
                items => list.Add(new string(items))
                );

            list.Sort();

            return(list.ToArray());
        }
        public void Generator_ThreadSafe_ParallelReaders()
        {
            var generator        = new CombinationGenerator(StandardKeypad);
            var threadIdByNumber = new ConcurrentDictionary <string, int>();

            generator
            .Generate(TEST_PHONE_NUMBER)
            .Take(100)
            .AsParallel()
            .ForAll(n =>
                    threadIdByNumber.TryAdd(n, Thread.CurrentThread.ManagedThreadId));

            Assert.AreEqual(100, threadIdByNumber.Count());
            foreach (var kvp in threadIdByNumber.OrderBy(x => x.Key))
            {
                Console.WriteLine($"{kvp.Key} - {kvp.Value}");
            }
        }
        public void GenerateRightCombinationsForNEqualsTwo()
        {
            CombinationGenerator generator = new CombinationGenerator();
            var result = generator.Generate(12, 2);

            Assert.Equal(12, result.Count);
            Assert.Equal(new int[] { }, result[0]);
            Assert.Equal(new[] { 1 }, result[1]);
            Assert.Equal(new[] { 2 }, result[2]);
            Assert.Equal(new[] { 1, 1 }, result[3]);
            Assert.Equal(new[] { 1, 2 }, result[4]);
            Assert.Equal(new[] { 2, 2 }, result[5]);
            Assert.Equal(new[] { 1, 1, 1 }, result[6]);
            Assert.Equal(new[] { 1, 1, 2 }, result[7]);
            Assert.Equal(new[] { 1, 2, 2 }, result[8]);
            Assert.Equal(new[] { 2, 2, 2 }, result[9]);
            Assert.Equal(new[] { 1, 1, 1, 1 }, result[10]);
            Assert.Equal(new[] { 1, 1, 1, 2 }, result[11]);
        }
        public void Combination()
        {
            var generator = new CombinationGenerator<string>(new[] { "a", "b", "c", "d", "e" }, 2);
            var results = generator.ToArray();
            string[][] expected = {
                                      new[] { "a", "b" },
                                      new[] { "a", "c" },
                                      new[] { "a", "d" },
                                      new[] { "a", "e" },
                                      new[] { "b", "c" },
                                      new[] { "b", "d" },
                                      new[] { "b", "e" },
                                      new[] { "c", "d" },
                                      new[] { "c", "e" },
                                      new[] { "d", "e" }
                                  };

            Assert.AreEqual(expected.Length, results.Length);
            Assert.IsTrue(expected.Select((x, i) => x.SequenceEqual(results[i])).All(x => x));
        }
Beispiel #27
0
        public IList <IList <int> > Subsets(int[] nums)
        {
            IList <IList <int> > list = new List <IList <int> >();

            CombinationGenerator.Generate(nums.Length, new[] { false, true }, flags => {
                List <int> items = new List <int>();

                for (int index = 0; index < flags.Length; index++)
                {
                    if (flags[index])
                    {
                        items.Add(nums[index]);
                    }
                }

                list.Add(items);
            });

            return(list);
        }
Beispiel #28
0
    // TODO: Optimize
    static ICollection <Tree> FindAllSubTreesWithSum(int sum)
    {
        var results = new List <Tree>();

        foreach (int root in FindAllNodes())
        {
            var currentQueue = new Queue <Tuple <Tree, int> >();
            currentQueue.Enqueue(new Tuple <Tree, int>(
                                     new Tree(true)
            {
                new KeyValuePair <int, ICollection <int> >(root, new int[0])
            },
                                     root
                                     ));

            while (currentQueue.Count != 0)
            {
                var current = currentQueue.Dequeue();

                if (current.Item2 > sum)
                {
                    continue;
                }

                if (current.Item2 == sum)
                {
                    results.Add(current.Item1);
                }

                // TODO
                foreach (var nextNode in CombinationGenerator.Generate())
                {
                    var nextTree = current.Item1.Clone();
                }
            }
        }

        return(results);
    }
Beispiel #29
0
        public List <Course> GetRecommendation(int studentId, FilterModel filterModel)
        {
            var availableCourses = GetUnlockedCourses(studentId).ToList();

            if (!filterModel.AvoidRetakeable)
            {
                availableCourses = availableCourses.Union(GetRetakeAbleCourses(studentId)).ToList();
            }
            var courseCombinations = CombinationGenerator.GetAllCombinations <Course>(availableCourses);

            courseCombinations = GetValidCreditCourseCombinations(courseCombinations, filterModel.NumberOfCredits);
            if (filterModel.AvoidClashExams)
            {
                courseCombinations = GetNoClashExamsCombinations(courseCombinations);
            }
            if (filterModel.AvoidTwoExamsInADay)
            {
                courseCombinations = GetNoMultipleExamsInADayCombinations(courseCombinations, 2);
            }
            if (filterModel.AvoidThreeExamsInADay)
            {
                courseCombinations = GetNoMultipleExamsInADayCombinations(courseCombinations, 3);
            }
            List <WarehousePredict> warehouses = CreateWarehouse(courseCombinations, studentId);
            var    result   = GetPrediction(warehouses);
            int    maxIndex = 0;
            double maxValue = 0;

            for (int i = 0; i < result.Length; i++)
            {
                if (result[i] > maxValue)
                {
                    maxValue = result[i];
                    maxIndex = i;
                }
            }
            return(courseCombinations[maxIndex]);
        }
Beispiel #30
0
 public IEnumerator <IEnumerable <T> > GetEnumerator()
 {
     if (_numberOfElements == 1)
     {
         foreach (var element in _setOfValues)
         {
             yield return(Enumerable.Repeat(element, 1));
         }
     }
     else
     {
         for (int i = _startIndex; i < _setOfValues.Length; i++)
         {
             T   element     = _setOfValues.ElementAt(i);
             var otherValues = _setOfValues.Skip(i + 1);
             CombinationGenerator <T> restOfTheCombinations = new CombinationGenerator <T>(otherValues, _numberOfElements - 1);
             foreach (var combination in restOfTheCombinations)
             {
                 yield return(Enumerable.Repeat(element, 1).Concat(combination));
             }
         }
     }
 }
        public static void Main(string[] args)
        {
            var logger = new ConsoleLogger();
            var reader = new ConsoleReader();

            // Task 1 -> Write a recursive program that simulates the execution of n nested loopsfrom 1 to n.
            var recLoops = new RecursiveSimulation(logger);

            recLoops.LoopsSimulation(3);

            // Task 2 -> Write a recursive program for generating and printing all the combinations with duplicatesof k elements from n-element set.
            var combinations = new CombinationGenerator(logger);

            combinations.CombinationsWithRepetitions(5, 3);

            // Task 3 -> Modify the previous program to skip duplicates
            combinations.CombinationsWithouthRepetitions(3, 2);

            // Task 4 -> Write a recursive program for generating and printing all permutations of the numbers 1, 2, ..., n for given integer number n

            var permutations = new Permutation(logger);

            permutations.PrintPermutations(3);

            // Task 5 -> Write a recursive program for generating and printing all ordered k-element subsets from n-element set (variations Vkn).
            var set        = new string[] { "hi", "a", "b", "c" };
            var collection = new List <string>();
            var variations = new VariationGenerator().GetVariations(set, collection, 3, 2);

            logger.WriteLine(string.Join(", ", collection));

            // Task 6 -> Write a program for generating and printing all subsets of k strings from given set of strings.
            var generator = new SubsetStrings(logger);
            var words     = new string[] { "test", "rock", "fun", "recursion" };

            generator.GenerateSubsets(words, 2);
        }
        public void Generator_Generate_RequiresInputhoneNumber()
        {
            var generator = new CombinationGenerator(StandardKeypad);

            generator.Generate(null).ToList();
        }
Beispiel #33
0
            /// <summary>
            /// Generate all possible permutations of length nChosen.
            /// </summary>
            /// <param name="nChosen">nChosen must be ≥ 0 and ≤ data.Length</param>
            public List<double[]> GetPermutations(int nChosen)
            {
                if (nChosen < 0)
                    throw new ArgumentException("nChosen cannot be less than zero. nChosen must be ≥ 0 and ≤ data.Length");
                if (nChosen > _data.Length)
                    throw new ArgumentException("nChosen cannot be less than zero. nChosen must be ≥ 0 and ≤ data.Length");
                if (nChosen == 0)
                    return new List<double[]> { new double[0] };

                if (nChosen == _data.Length)
                    return GetPermut(_data);

                CombinationGenerator cg = new CombinationGenerator(_data);
                List<double[]> combins = cg.Combinations(nChosen);
                List<double[]> permuts = new List<double[]>();
                foreach (double[] da in combins)
                {
                    permuts.AddRange(GetPermut(da));
                }
                return permuts;
            }
Beispiel #34
0
        public static void MinimumDominatingSet(Graph g, int seed)
        {
            Output.WriteLine("[Minimum Dominating Set Output]");

            //MDS takes an undirected graph
            CombinationGenerator cg      = new CombinationGenerator(g.GetVertices().Count, seed);
            bool            setFound     = false;
            List <Vertex>   verts        = new List <Vertex>(g.GetVertices().Count);
            List <Vertex>   neighborhood = new List <Vertex>();
            List <Vertex[]> domSet       = new List <Vertex[]>();
            bool            restricted   = false;
            int             setLen       = 0;

            while (cg.HasNext())
            {
                int[] array = cg.GetNext();
                int[] tally = new int[array.Length];
                array.CopyTo(tally, 0);

                Vertex[]      possibleSet        = new Vertex[cg.CurrentLevel()];
                int           possibleSetCounter = 0;
                List <Vertex> neighbors          = new List <Vertex>();

                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i] != 1)
                    {
                        continue;
                    }

                    possibleSet[possibleSetCounter] = g.GetVertices()[i];
                    possibleSetCounter++;

                    neighbors.AddRange(g.GetVertices()[i].GetAllNeighbors());
                }

                foreach (Vertex v in neighbors)
                {
                    int index = g.GetVertices().IndexOf(v);
                    if (index == -1)
                    {
                        continue;
                    }

                    tally[index] = 1;
                }

                bool validSet = true;
                for (int i = 0; i < tally.Length; i++)
                {
                    if (tally[i] != 1)
                    {
                        validSet = false;
                        break;  //we break, because we only want to find one dominating set
                    }
                }

                if (validSet)
                {
                    setFound = true;
                    if (!restricted)
                    {
                        cg.RestrictToCurrentLevel();
                        restricted = true;
                        setLen     = possibleSet.Length;
                    }

                    if (setLen == possibleSet.Length)
                    {
                        domSet.Add(possibleSet);
                        break;
                    }
                }
            }

            //Tally method
            //Initiate tally to be the generated array, (create a copy!)
            //go through the neighborhood of each vertex with value 1
            //for each neighbor, change their value in the tally to 1
            //If tally is all 1s, then you have everything

            if (setFound)
            {
                //print out the found set and find the others
                Output.WriteLine("Found minimum dominating sets:");
                foreach (Vertex[] v in domSet)
                {
                    string separator = "";
                    for (int i = 0; i < v.Length; i++)
                    {
                        Output.Write(separator + v[i].ToString());
                        separator = ",";
                    }
                    Output.WriteLine();
                }
            }

            Output.WriteLine("[End Minimum Dominating Set Output]");
        }