Generate permutations of a given sequence of values contains unique or non-unique elements.
Example #1
0
 public void Example3()
 {
     Assert.AreEqual(new List <string> {
         "aabb", "abab", "abba", "baab", "baba", "bbaa"
     },
                     Permutations.SinglePermutations("aabb").OrderBy(x => x).ToList());
 }
        private void TestInvalidTiles(int[] tiles, int invalidTileValue)
        {
            if ((tiles is null) || (tiles.Length != 6))
            {
                Assert.Fail("test data invalid");
            }

            Permutations <int> permutations = new Permutations <int>(tiles);

            foreach (IList <int> permutation in permutations)
            {
                SetTiles(permutation);
                Assert.IsTrue(nvm.HasErrors);

                for (int index = 0; index < permutation.Count; index++)
                {
                    if (permutation[index] == invalidTileValue)
                    {
                        Assert.IsNotNull(nvm.GetErrors(propertyNames[index]));
                    }
                    else
                    {
                        Assert.IsNull(nvm.GetErrors(propertyNames[index]));
                    }
                }
            }
        }
Example #3
0
        public static void DoTest()
        {
            var alphabets = "abcdefg";

            var permutations = Permutations.ComputeDistinct(alphabets);

            Debug.Assert(permutations.Count == 720);

            var one = "abcdefg";
            var two = "dabcgfe";

            Debug.Assert(Permutations.IsAnargram(one, two) == true);

            one = "123456";
            two = "789123";
            Debug.Assert(Permutations.IsAnargram(one, two) == false);

            one = "abc";
            two = "bbb";
            Debug.Assert(Permutations.IsAnargram(one, two) == false);

            one = "acdf";
            two = "bcde";
            Debug.Assert(Permutations.IsAnargram(one, two) == false);

            one = "I am legion";    // L is small
            two = "Legion I am";    // L is capital
            Debug.Assert(Permutations.IsAnargram(one, two) == false);

            one = "I am legion";    // L is small
            two = "legion I am";    // L is small
            Debug.Assert(Permutations.IsAnargram(one, two) == true);
        }
Example #4
0
 /// <summary>
 /// Initialize the variations for constructors.
 /// </summary>
 /// <param name="values">List of values to select variations from.</param>
 /// <param name="lowerIndex">The size of each variation set to return.</param>
 /// <param name="type">The type of variations set to generate.</param>
 private void Initialize(IList <T> values, int lowerIndex, GenerateOption type)
 {
     myMetaCollectionType = type;
     myLowerIndex         = lowerIndex;
     myValues             = new List <T>();
     myValues.AddRange(values);
     if (type == GenerateOption.WithoutRepetition)
     {
         List <int> myMap = new List <int>();
         int        index = 0;
         for (int i = 0; i < myValues.Count; ++i)
         {
             if (i >= myValues.Count - myLowerIndex)
             {
                 myMap.Add(index++);
             }
             else
             {
                 myMap.Add(Int32.MaxValue);
             }
         }
         myPermutations = new Permutations <int>(myMap);
     }
     else
     {
         ;     // myPermutations isn't used.
     }
 }
Example #5
0
        override public void Evaluate(int SpreadMax)
        {
            if (FInput.IsChanged || FWithRepetition.IsChanged)
            {
                buffer.Clear();

                for (int i = 0; i < FInput.SliceCount; i++)
                {
                    buffer.Add(FInput[i]);
                }

                if (FWithRepetition[0])
                {
                    go = GenerateOption.WithRepetition;
                }
                else
                {
                    go = GenerateOption.WithoutRepetition;
                }

                Permutations <T> permutations = new Permutations <T>(buffer, go);

                FOutput.SliceCount = 0;
                foreach (IList <T> p in permutations)
                {
                    FOutput.AddRange(p);
                }

                FCount.SliceCount = 1;
                FCount[0]         = (int)permutations.Count;
            }
        }
Example #6
0
        /// <summary>
        /// Initialize the combinations by settings a copy of the values from the
        /// </summary>
        /// <param name="values">List of values to select combinations from.</param>
        /// <param name="lowerIndex">The size of each combination set to return.</param>
        /// <param name="type">The type of Combinations set to generate.</param>
        /// <remarks>
        /// Copies the array and parameters and then creates a map of booleans that will
        /// be used by a permutations object to refence the subset.  This map is slightly
        /// different based on whether the type is with or without repetition.
        ///
        /// When the type is WithoutRepetition, then a map of upper index elements is
        /// created with lower index false's.
        /// E.g. 8 choose 3 generates:
        /// Map: {1 1 1 1 1 0 0 0}
        /// Note: For sorting reasons, false denotes inclusion in output.
        ///
        /// When the type is WithRepetition, then a map of upper index - 1 + lower index
        /// elements is created with the falses indicating that the 'current' element should
        /// be included and the trues meaning to advance the 'current' element by one.
        /// E.g. 8 choose 3 generates:
        /// Map: {1 1 1 1 1 1 1 1 0 0 0} (7 trues, 3 falses).
        /// </remarks>
        private void Initialize(ICollection <T> values, Int32 lowerIndex, GenerateOption type)
        {
            Type       = type;
            LowerIndex = lowerIndex;
            _values    = new List <T>();
            _values.AddRange(values);
            List <Boolean> map = new List <Boolean>();

            if (type == GenerateOption.WithoutRepetition)
            {
                map.AddRange(_values.Select((t, i) => i < _values.Count - LowerIndex));
            }
            else
            {
                for (Int32 i = 0; i < values.Count - 1; ++i)
                {
                    map.Add(true);
                }

                for (Int32 i = 0; i < LowerIndex; ++i)
                {
                    map.Add(false);
                }
            }

            _permutations = new Permutations <Boolean>(map);
        }
Example #7
0
        public override object Run(RunModes runMode, object input, bool Logging)
        {
            var currentSeed = 345;

            while (true)
            {
                var nextSeed = SeedCubes(currentSeed);

                var foundPermsMaster = CubesDictionary[currentSeed].ToList();
                foreach (var cube in CubesDictionary[currentSeed])
                {
                    var count      = 0;
                    var foundPerms = new List <long>();
                    foreach (var cube2 in foundPermsMaster)
                    {
                        if (Permutations.IsPermutations(cube, cube2) && !foundPerms.Contains(cube))
                        {
                            count++;
                            foundPerms.Add(cube);
                        }
                        if (count == 5)
                        {
                            return(cube);
                        }
                    }
                    foundPermsMaster.RemoveAll(foundPerms.Contains);
                }
                currentSeed = nextSeed;
            }
        }
Example #8
0
        public override object Run(RunModes runMode, object input, bool Logging)
        {
            int replacePrimeFamilyCount = (int)input;

            Primes.InitPrimes();
            Primes.TrimPrimes(9, 1000000);
            var primeList       = Primes.AllPrimes.OrderBy(p => p);
            int primeInitLength = 0;

            foreach (var start in primeList)
            {
                var stringStart       = start.ToString();
                var stringStartLength = stringStart.Length;
                if (stringStartLength > primeInitLength)
                {
                    Primes.InitPrimes((long)Math.Pow(10, stringStartLength));
                    Primes.TrimPrimes((long)(Math.Pow(10, stringStartLength - 1) - 1), (long)Math.Pow(10, stringStartLength));
                    primeInitLength = stringStartLength;
                }
                for (int indecesToReplace = 1; indecesToReplace < stringStartLength; indecesToReplace++)
                {
                    var indeces = Combinations.ChooseStringIndeces(indecesToReplace, stringStartLength);
                    foreach (var index in indeces)
                    {
                        var permutations = Permutations.GenerateReplacements(stringStart, index);
                        if (permutations.Count() >= replacePrimeFamilyCount && permutations.Count(Primes.IsPrime) >= replacePrimeFamilyCount)
                        {
                            return(permutations.Min());
                        }
                    }
                }
            }
            return(0);
        }
Example #9
0
        private void GeneratePermutationsBtn_Click(object sender, EventArgs e)
        {
            if (!IsInputValid(InputField.Text))
            {
                MessageBox.Show("Please populate input field by either typing or importing file");
                return;
            }

            ClearAllFields();

            Stopwatch watch = new Stopwatch();

            watch.Start();

            var permutable = InputField.Text.ToCharArray();

            var permutations = Permutations.Generate(permutable);

            permutations.ToList().ForEach(x => PermutationsField.Text += new string(x) + "\r\n");

            PermutationsCountField.Text = permutations.Count().ToString();

            Permutations.GetMatches(permutable, permutations).ToList().ForEach(x => MatchingPermutationsField.Text += new string(x) + "\r\n");

            watch.Stop();

            TimeField.Text = watch.ElapsedMilliseconds.ToString();
        }
Example #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Input a string: ");
            string s  = Console.ReadLine();
            var    sC = (from entry in s select entry).ToList();

            bool   boolSol = false;
            var    p = new Permutations <char>(sC, GenerateOption.WithoutRepetition);
            string temp = "", ts = "";

            foreach (var v in p)
            {
                foreach (var k in v)
                {
                    temp += k;
                }

                ts = new string(temp.ToCharArray().Reverse().ToArray());

                if (temp == ts)
                {
                    boolSol = true;
                    break;
                }

                temp = "";
            }

            Console.WriteLine($">< {boolSol} ><");
            Console.ReadLine();
        }
        public void GeneratedPermutationsCountTest()
        {
            char[] permutable   = new char[] { 'A', 'B', 'C', 'D' };
            var    permutations = Permutations.Generate(permutable);

            Assert.AreEqual(24, permutations.Count());
        }
Example #12
0
        public void Basic()
        {
            var p      = new Permutations();
            var result = p.Permute(new[] { 1, 2, 3 });

            var expected = new List <IList <int> >()
            {
                new List <int>()
                {
                    1, 2, 3
                },
                new List <int>()
                {
                    1, 3, 2
                },
                new List <int>()
                {
                    2, 1, 3
                },
                new List <int>()
                {
                    2, 3, 1
                },
                new List <int>()
                {
                    3, 2, 1
                },
                new List <int>()
                {
                    3, 1, 2
                },
            };

            Assert.Equal(expected, result);
        }
        public static List <List <int> > GetGenotypeCombinations(int numberOfStates, int currentState)
        {
            const int diploidState      = 2;
            const int maxNumberOfStates = 4;

            if (numberOfStates > maxNumberOfStates)
            {
                Console.WriteLine($"CanvasPartition.exe: number of states/samples {numberOfStates} is too large for full combinatorial enumeration\n" +
                                  $"Settings to the default number {maxNumberOfStates}");
                numberOfStates = maxNumberOfStates;
            }

            var upperSetBound   = SpecialFunctions.Factorial(numberOfStates) * SpecialFunctions.Factorial(numberOfStates / 2);
            var allCombinations = new List <List <int> >(Convert.ToInt32(upperSetBound));

            for (int numberOfDiploidStates = 1; numberOfDiploidStates < numberOfStates; numberOfDiploidStates++)
            {
                IEnumerable <int> states = Enumerable.Repeat(currentState, numberOfStates - numberOfDiploidStates)
                                           .Concat(Enumerable.Repeat(diploidState, numberOfDiploidStates));
                var permutations = new Permutations <int>(states.ToList(), GenerateOption.WithoutRepetition);
                //List<List<int>> permutations = null; // %%%
                var list = permutations.Select(x => x.ToList()).ToList();
                allCombinations.AddRange(list);
            }
            return(allCombinations);
        }
Example #14
0
        public void shouldreturnvalidresultfoBasicMethod()
        {
            var input = new int[] { 1, 3, 5 };

            var expectedResult = new List <List <int> > {
                new List <int> {
                    1, 3, 5
                },
                new List <int> {
                    1, 5, 3
                },
                new List <int> {
                    3, 1, 5
                },
                new List <int> {
                    3, 5, 1
                },
                new List <int> {
                    5, 1, 3
                },
                new List <int> {
                    5, 3, 1
                }
            };


            var result     = Permutations.findPermutations(input);
            var listResult = CollectionEquivalence.AreEqual <int>(result, expectedResult);

            Assert.True(listResult);
        }
Example #15
0
        public void shouldReturnFalseIfStringsAreNotTheSameLength()
        {
            var s1 = "abc";
            var s2 = "abcd";

            Assert.False(Permutations.IsPermutation(s1, s2));
        }
Example #16
0
 /// <summary>
 /// Construct a enumerator with the parent object.
 /// </summary>
 /// <param name="source">The source Permutations object.</param>
 public Enumerator(Permutations <T> source)
 {
     myParent = source;
     myLexicographicalOrders = new int[source.myLexicographicOrders.Length];
     source.myLexicographicOrders.CopyTo(myLexicographicalOrders, 0);
     Reset();
 }
Example #17
0
    /// <summary>
    /// Initialize the combinations by settings a copy of the values from the
    /// </summary>
    /// <param name="values">List of values to select combinations from.</param>
    /// <param name="lowerIndex">The size of each combination set to return.</param>
    /// <param name="type">The type of Combinations set to generate.</param>
    /// <remarks>
    /// Copies the array and parameters and then creates a map of booleans that will
    /// be used by a permutations object to refence the subset.  This map is slightly
    /// different based on whether the type is with or without repetition.
    ///
    /// When the type is WithoutRepetition, then a map of upper index elements is
    /// created with lower index false's.
    /// E.g. 8 choose 3 generates:
    /// Map: {1 1 1 1 1 0 0 0}
    /// Note: For sorting reasons, false denotes inclusion in output.
    ///
    /// When the type is WithRepetition, then a map of upper index - 1 + lower index
    /// elements is created with the falses indicating that the 'current' element should
    /// be included and the trues meaning to advance the 'current' element by one.
    /// E.g. 8 choose 3 generates:
    /// Map: {1 1 1 1 1 1 1 1 0 0 0} (7 trues, 3 falses).
    /// </remarks>
    private void Initialize(IList <T> values, int lowerIndex, GenerateOption type)
    {
        myMetaCollectionType = type;
        myLowerIndex         = lowerIndex;
        myValues             = new List <T>();
        myValues.AddRange(values);
        List <bool> myMap = new List <bool>();

        if (type == GenerateOption.WithoutRepetition)
        {
            for (int i = 0; i < myValues.Count; ++i)
            {
                if (i >= myValues.Count - myLowerIndex)
                {
                    myMap.Add(false);
                }
                else
                {
                    myMap.Add(true);
                }
            }
        }
        else
        {
            for (int i = 0; i < values.Count - 1; ++i)
            {
                myMap.Add(true);
            }
            for (int i = 0; i < myLowerIndex; ++i)
            {
                myMap.Add(false);
            }
        }
        myPermutations = new Permutations <bool>(myMap);
    }
Example #18
0
        public void PermutationsTest()
        {
            var expected = new HashSet <string>
            {
                "01", "12", "02",
                "10", "21", "20",
            };

            // Should return all combinations of {0, 1, 2}
            foreach (var x in Permutations.Integers(3, 2))
            {
                int first  = x[0];
                int second = x[1];
                var str    = $"{first}{second}";

                if (expected.Contains(str))
                {
                    expected.Remove(str);
                }
                else
                {
                    Assert.Fail($"{str} was not in the set when it should be");
                }
            }

            Assert.AreEqual(0, expected.Count);
        }
Example #19
0
        static int ShortestCircuit()
        {
            int        result = int.MaxValue;
            int        curr;
            List <int> way;
            List <int> perm = new List <int>();

            for (int i = 1; i <= Verticles; ++i)
            {
                perm.Add(i);
            }
            var p = new Permutations <int>(perm);

            foreach (var v in p)
            {
                curr = 0;
                way  = new List <int>()
                {
                    0
                };
                way.AddRange(v);
                for (int i = 0; i <= Verticles; ++i)
                {
                    curr += graph[way[i]][way[(i + 1) % Verticles]].Length;
                }
                result = Math.Min(result, curr);
            }
            return(result);
        }
        public void Permutation_Test()
        {
            int[] nums   = { 1, 2, 3 };
            var   result = Permutations.Permutations_(nums, 3);

            Assert.AreEqual(new List <string>(), result);
        }
Example #21
0
        public ActionResult Problem41(uint n)
        {
            if (n > 9)
            {
                n = 9;
            }

            // Set up prime calculator
            var cal = new PrimeCalculator();

            // Keep trying until we run out of digits.
            while (n > 0)
            {
                List <int> digits       = Enumerable.Range(1, (int)n).ToList();
                var        permutations = new Permutations <int>(digits);

                var allPrimes = permutations.Select(numList => numList.MakeNumber())
                                .Where(num => cal.IsPrimeAutoExpand(num)).ToList();

                // If there is at least 1 prime with n-digit, find the maximum amongst these primes and
                // that's the answer
                if (allPrimes.Count > 0)
                {
                    ulong max = allPrimes.Max();
                    return(ViewAnswer(41, "The maximum " + n + "-digit pandigital prime is", max));
                }

                // Otherwise, reduce number of digits and try again.
                --n;
            }

            return(ViewAnswer(41, "No n-digit pandigital prime found.", 0));
        }
        public void PermutationEmpty()
        {
            var testArr = Array.Empty <int>();
            var ex      = Assert.Throws <ArgumentException>(() => Permutations.OfSampleSize(someList: testArr, 1).ToList(), "Its expected that an empty array is not a valid argument");

            Assert.That(ex.Message, Is.EqualTo("someList cannot be empty."));
        }
Example #23
0
        public static void C(string name, string type, int length, string output)
        {
            int           count  = (int)Math.Pow(10, length);
            List <string> list   = new List <string>(10000);
            string        format = "D" + length;

            for (int i = 0; i < count; i++)
            {
                var digits             = i.ToString(format).ToArray();
                Permutations <char> p  = new Permutations <char>(digits, length);
                List <string>       pn = p.Get(",");
                if (pn.Exists(x => list.Contains(x)))
                {
                    continue;
                }

                list.Add(i.Format(format, ","));
            }

            if (output.Equals("txt"))
            {
                SaveToText(name, type, list);
                return;
            }

            SaveToDB(name, type, list);
        }
Example #24
0
        public IEnumerable <Processo> ProcessarFila(IEnumerable <Processo> processos)
        {
            var   indices             = Enumerable.Range(0, processos.Count()).ToList();
            var   permutacoes         = new Permutations <int>(indices);
            var   filaMenorCusto      = new List <Processo>();
            float?filaMenorCustoTotal = null;

            foreach (var permutacao in permutacoes)
            {
                var sequenciaExecucao = new List <Processo>();

                foreach (var indice in permutacao)
                {
                    sequenciaExecucao.Add(processos.ElementAt(indice));
                }

                var custo = CalcularCusto(sequenciaExecucao);

                if (filaMenorCustoTotal == null || filaMenorCustoTotal > custo)
                {
                    filaMenorCustoTotal = custo;
                    filaMenorCusto      = sequenciaExecucao;
                }
            }

            return(filaMenorCusto);
        }
Example #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("Input all digits in a line i.e. 123: ");
            var n  = Console.ReadLine();
            var sN = (from entry in n select entry).ToList();

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            var p = new Permutations <char>(sN, GenerateOption.WithoutRepetition);

            stopwatch.Stop();

            string temp = "";

            Console.WriteLine(stopwatch.Elapsed);
            Console.WriteLine("\nHere are all the permutations:");

            foreach (var v in p)
            {
                temp = string.Join("", v);

                Console.WriteLine(temp);

                temp = "";
            }
        }
        public string ShowPermutationDetails(string documentContent)
        {
            string cleanPermutation;
            string key;
            bool   isContentOk = Descriptor.GetKey(documentContent, out cleanPermutation, out key);

            if (!isContentOk)
            {
                return("The document content you entered is not legal");
            }

            // key doesn't exist
            string msg = String.Format("\nThe document {0} doesn't exist in the system", documentContent);

            if (!_documentsManagementSystem.ContainsKey(key))
            {
                return(msg);
            }

            // key exist but permutation doesn't exist
            Permutations toSearch = new Permutations(cleanPermutation, null);
            Permutations foundItem;
            bool         isPermutationExist = _documentsManagementSystem[key].Permutations.Search(toSearch, out foundItem);

            msg = String.Format("\nThe permutation {0} doesn't exist in the system", cleanPermutation);
            if (!isPermutationExist)
            {
                return(msg);
            }

            int      numOfPermutationCopies = foundItem.Count;
            DateTime timeStamp = foundItem.Ref.Data.Timestamp;

            return(string.Format("\nFor the document permutation of {0}, there are {1} numbers of copies, and the last copy was updated in {2}", documentContent, numOfPermutationCopies, timeStamp));
        }
Example #27
0
        /// <summary>
        /// 可重复组合
        /// </summary>
        public static void Cr(string name, string type, int length, string output)
        {
            List <List <int> > lists = length == 2 ? GetPr2() : GetPr3();
            List <string>      clist = new List <string>(360);

            foreach (var list in lists)
            {
                Permutations <int> p  = new Permutations <int>(list, length);
                List <string>      pn = p.Get(",");
                if (pn.Exists(x => clist.Contains(x)))
                {
                    continue;
                }

                clist.Add(list.Format(","));
            }

            if (output.Equals("txt"))
            {
                SaveToText(name, type, clist);
                return;
            }

            SaveToDB(name, type, clist);
        }
        public string FindClosestPermutation(string permutation)
        {
            string cleanPermutation;
            string key;
            string msg = string.Format("The permutation {0} was not found, and also wasn't found a following permutation", permutation);

            if (!Descriptor.GetKey(permutation, out cleanPermutation, out key))
            {
                return("The document content you entered is not legal");
            }

            if (!_documentsManagementSystem.ContainsKey(key))
            {
                return(string.Format("The document for the permutation {0}, doesn't exist in the system", permutation));
            }

            Permutations itemToFind = new Permutations(cleanPermutation, null);
            Permutations foundItem;
            bool         foundNext = _documentsManagementSystem[key].Permutations.SearchNext(itemToFind, out foundItem);

            if (foundNext)
            {
                return(ShowPermutationDetails(foundItem.Permutation));
            }
            return(msg);
        }
Example #29
0
        public string SolvePart1()
        {
            // Do for all combinations of Phase
            var permutations = new Permutations <int>(Enumerable.Range(0, 5).ToList());
            var maxOutput    = int.MinValue;

            foreach (var permutation in permutations)
            {
                // For Amp A -> E
                var signal = 0;
                foreach (int phase in permutation)
                {
                    var amplifier = new IntCodeMachine.IntCodeMachine(Input, new[] { phase, signal });
                    amplifier.Execute(false);
                    signal = int.Parse(amplifier.Outputs.First());
                }

                // Record final output if higher than previous final
                if (signal > maxOutput)
                {
                    maxOutput = signal;
                }
            }

            return($"Part 1: {maxOutput}");
        }
Example #30
0
        internal IPropertyValue Actual(string label)
        {
            if (_collectionNames.IsNullOrEmpty())
            {
                return(Label == label ? this : null); // this should shortcut nicely when there is no collection.
            }

            var values = Permutations.Where(each => ParentPropertySheet.ResolveMacros(Label, each) == label)
                         .SelectMany(each => _values
                                     .Select(value => ParentPropertySheet.ResolveMacros(value, each)))
                         .ToArray();

            if (values.Length > 0)
            {
                return(new ActualPropertyValue {
                    SourceLocation = SourceLocation,
                    IsSingleValue = values.Length == 1,
                    HasMultipleValues = values.Length > 1,
                    SourceString = "",
                    Value = values[0],
                    Values = values,
                    ParentRule = ParentPropertyRule.ParentRule
                });
            }

            return(null);
        }
Example #31
0
        /// <summary>
        /// Конструктор с параметрами
        /// </summary>
        /// <param name="key1"> Ключ для первого прохода шифрования. </param>
        /// <param name="key2"> Ключ для второго прохода шифрования. </param>
        public BitMaps(byte[] key1, byte[] key2)
        {
            // Создаем ключ на базе двух ключей
            BitmapKey = CryforceUtilities.MergeArrays(key1, key2);
            Bitmaps = new Permutations<int>(new[] {0, 1, 2, 3, 4, 5, 6, 7}).MakePermutationsSet(); // 40320 перестановок 8 бит
            BitmapsIdx = BitmapKeyIdx = 0;

            // Производим самообновление ключа
            RefreshKey();
        }
Example #32
0
        static void Main(string[] args)
        {
            List<string> input = File.ReadAllLines("Input.txt").ToList();
            List<string> locations = new List<string>();
            List<Journey> journeys =
                input.Select(s => s.Split(' '))
                     .Select(
                         parts =>
                         new Journey {DepartFrom = parts[0], TravelTo = parts[2], Distance = Convert.ToInt32(parts[4])})
                     .ToList();

            foreach (Journey journey in journeys)
            {
                //Console.WriteLine($"{journey.DepartFrom}, {journey.TravelTo}: {journey.Distance}");
                locations.AddRange(new[]
                                   {
                                       journey.DepartFrom,
                                       journey.TravelTo
                                   }
                    );
            }
            locations = locations.Distinct().ToList();

            Permutations<string> trips = new Permutations<string>(locations);
            List<int> totalDistances = new List<int>();
            Console.WriteLine("Crunching numbers...");
            foreach (IList<string> trip in trips)
            {
                //Console.WriteLine(string.Join(", ", trip));
                int totalDistance = 0;
                for (int i = 0; i < trip.Count - 1; i++)
                {
                    Journey nextJourney = journeys.FirstOrDefault(
                        x =>
                        (x.DepartFrom.Equals(trip[i]) && x.TravelTo.Equals(trip[i + 1]) ||
                         x.TravelTo.Equals(trip[i]) && x.DepartFrom.Equals(trip[i + 1])));
                    if (nextJourney == null)
                    {
                        Console.WriteLine($"!?ERROR?! Could not find Journey from {trip[i]} to {trip[i + 1]}!");
                        continue;
                    }
                    totalDistance += nextJourney.Distance;
                }
                totalDistances.Add(totalDistance);

                //Console.WriteLine(totalDistance);
            }
            Console.WriteLine($"Shortest distance: {totalDistances.Min()}");
            Console.WriteLine($"Longest distance: {totalDistances.Max()}");
            Console.Write("Press any key...");
            Console.ReadKey();
        }
    static void Main()
    {
        int n = Int32.Parse(Console.ReadLine());
        int[] arr = new int[n];

        for (int i = 0; i < n; i++)
        {
            arr[i] = i + 1;
        }

        Permutations p = new Permutations();
        p.setper(arr);
    }
        public void Generate_Permutations_Without_Repetition_On_3_Unique_Input_Items_Should_Create_12_Output_Permutations()
        {
            var integers = new List<int> { 1, 2, 3 };

            var p = new Permutations<int>(integers, GenerateOption.WithoutRepetition);

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

            Assert.AreEqual(6, p.Count);
        }
        public static void Main(string[] args)
        {
            bool isFirstRun = true;
            while (true)
            {
                if (isFirstRun)
                {
                    System.Console.WriteLine("UWW CS215 Fano Plane Automorphism Finder" + Environment.NewLine + "Authored by Connor Grady, Grant Jones, and Collin Stolpa");
                }
                else
                {
                    System.Console.WriteLine();
                }
                string input = CollectInput();

                string[] items = new string[7] { "1", "2", "3", "4", "5", "6", "7" };

                Permutations permutations = new Permutations();
                List<List<string>> results = permutations.GeneratePermutations(items.ToList());
                //WritePermutations(results);

                switch (input)
                {
                    case "OutputPerms":
                        WritePermutations(results);
                        break;

                    case "OutputAutos":
                        // Now that we have the Permutations, let's check for the automorphisms
                        List<List<string>> automorphisms = results.Where(IsAutomorphism).ToList();

                        // Convert to Cycle Notation
                        List<string> automorphicCycles = automorphisms.Select(perm => permutations.ToCycleNotation(results.FirstOrDefault(), perm)).ToList();

                        // Write cycles to the Console
                        WriteCycles(automorphicCycles, automorphisms.Select(auto => string.Join("", auto)).ToList());
                        break;

                    default:
                        System.Console.WriteLine("ERROR: No valid selection detected. Please try again...");
                        break;
                }

                isFirstRun = false;
            }
        }
Example #36
0
 static void Main()
 {
     int N = GetValidInput("Enter the upper margin for the permutations range( 1 to N ): ", 2);
     //build the array
     List<int> numbers = new List<int>();
     for (int i = 1; i <= N; i++)
     {
         numbers.Add(i);
     }
     //generate a permutations collection
     Permutations<int> permutations = new Permutations<int>(numbers);
     //print the elements in the collection
     foreach (IList<int> p in permutations)
     {
         foreach (var item in p)
         {
             Console.Write(item);
         }
         Console.WriteLine();
     }
 }
        /// <summary>
        /// Specifies whether the provided permutation is an automorphism of the Fano Plane Permutations.
        /// </summary>
        /// <param name="permutation">The permutation derived to check.</param>
        /// <returns>Boolean specifying whether the permutation is an automorphism.</returns>
        private static bool IsAutomorphism(List<string> permutation)
        {
            Permutations permutations = new Permutations();
            // Get the permutation as a set of 7 sets of 3 characters
            List<List<string>> permGroups = permutations.PermTo7SetsOf3(permutation);

            // Get the Fano Plane collection
            List<List<string>> fanoGroups = FanoPlane.GenerateCollection();

            // This will contain the result of all the "true" method comparisons
            // If there are 7 "true" bools at the end, then it is an automorphism
            List<bool> groupBools = new List<bool>(7);

            // For each 3-member group of the permutation
            foreach (List<string> permGroup in permGroups)
            {
                // True if there's at least one 3-member group in the fano plane collection that matches
                // this 3-member group of the permutation
                bool atLeastOneGroupMatches = false;

                // For each 3-member group in the fano collection, for the first group that matches all 3 members (regardless of order),
                // set atLeastOneGroupMatches = true, remove that 3-member group from the fano collection, and break from the loop
                foreach (List<string> fanoGroup in from fanoGroup in fanoGroups let charsMatch = permGroup.All(fanoGroup.Contains) where charsMatch select fanoGroup)
                {
                    atLeastOneGroupMatches = true;
                    fanoGroups.Remove(fanoGroup);
                    break;
                }

                // Add whatever the value of atLeastOneGroupMatches to the bool collection
                groupBools.Add(atLeastOneGroupMatches);
            }

            // Return a boolean whose value is true if the count of all "true" booleans in the bool collection is 7
            return groupBools.Count(x => x) == 7;
        }
        /// <summary>
        /// Returns all 10 digit pandigital numbers. Filters numbers that start with 0.
        /// </summary>
        public IEnumerable<long> GetPandigitalNumbers()
        {
            var numbers = Enumerable.Range(0, 10).ToList();

            var perms = new Permutations<int>(numbers, GenerateOption.WithoutRepetition).AsParallel()
                .Where(list => list[0] != 0)
                .Select(DigitHelper.ConvertToNumber);
            return perms;
        }
Example #39
0
 void DoArrayBuilder()
 {
     Permutations<int> intPer = new Permutations<int>(new int[] { 0, 1, 2, 3, 4 }, GenerateOption.WithoutRepetition);
     //生成颜色数组
     foreach (IList<int> item in intPer)
     {
         if (ConditionService.Verify14(item))
         {
             int[] ts = new int[5];
             item.CopyTo(ts, 0);
             _Colors.Add(ts);
         }
     }
     //生成国家数组
     foreach (IList<int> item in intPer)
     {
         if (ConditionService.Verify08(item))
         {
             int[] ts = new int[5];
             item.CopyTo(ts, 0);
             _Nationals.Add(ts);
         }
     }
     //生成饮料数组
     foreach (IList<int> item in intPer)
     {
         if (ConditionService.Verify09(item))
         {
             int[] ts = new int[5];
             item.CopyTo(ts, 0);
             _Drinks.Add(ts);
         }
     }
     //生成宠物数组
     foreach (IList<int> item in intPer)
     {
         int[] ts = new int[5];
         item.CopyTo(ts, 0);
         _Pets.Add(ts);
     }
     //生成香烟数组
     foreach (IList<int> item in intPer)
     {
         int[] ts = new int[5];
         item.CopyTo(ts, 0);
         _Cigarettes.Add(ts);
     }
     this.SetTotalLabel(_Colors.Count * _Nationals.Count * _Drinks.Count * _Pets.Count * _Cigarettes.Count);
     //_count = _Colors.Count + _Nationals.Count + _Drinks.Count + _Pets.Count + _Cigarettes.Count;
 }
        private int GetResultsForSet(IList<int> set)
        {
            var setPermutations = new Permutations<int>(set, GenerateOption.WithoutRepetition);

            var results = new HashSet<int>();

            bool shouldPrint = (set[0] == 1 && set[1] == 2 && set[2] == 5 && set[3] == 6);

            foreach (IList<int> nums in setPermutations)
            {
                foreach (IList<int> ops in operationVariations)
                {
                    // Possible bracket combinations:

                    int a = 0;

                    try
                    {
                        // (1 2)(3 4)
                        a = Add(
                            O(O(nums[0], nums[1], ops[0]), O(nums[2], nums[3], ops[2]), ops[1]),
                            results);

                        //if (shouldPrint)
                        //    Console.WriteLine(string.Format("({0} {1} {2}) {3} ({4} {5} {6}) = {7}",
                        //                      nums[0], Op(ops[0]), nums[1], Op(ops[1]), nums[2], Op(ops[2]), nums[3], a));
                    }
                    catch { }

                    try
                    {
                        // ((1 2)3) 4
                        a = Add(
                            O(O(O(nums[0], nums[1], ops[0]), nums[2], ops[1]), nums[3], ops[2]),
                            results);
                    }
                    catch { }

                    try
                    {
                        // (1(2 3)) 4
                        a = Add(
                            O(O(nums[0], O(nums[1], nums[2], ops[1]), ops[0]), nums[3], ops[2]),
                            results);

                        //if (shouldPrint)
                        //    Console.WriteLine(string.Format(" ({0} {1} ({2} {3} {4})) {5} {6} = {7}",
                        //                      nums[0], Op(ops[0]), nums[1], Op(ops[1]), nums[2], Op(ops[2]), nums[3], a));
                    }
                    catch { }

                    try
                    {
                        // 1 ((2 3)4)
                        a = Add(
                            O(nums[0], O(O(nums[1], nums[2], ops[1]), nums[3], ops[2]), ops[0]),
                            results);
                    }
                    catch { }

                    try
                    {
                        // 1 (2(3 4))
                        a = Add(
                            O(nums[0], O(nums[1], O(nums[2], nums[3], ops[2]), ops[1]), ops[0]),
                            results);
                    }
                    catch { }
                }
            }

            var ordered = results.OrderBy(o => o).ToList();

            int lastMax = 0;

            for (int counter = 1; counter < ordered.Count; counter++)
            {
                if (ordered[counter] != ordered[counter - 1] + 1)
                {
                    lastMax = ordered[counter - 1];

                    break;
                }
            }

            //if (shouldPrint)
            //{
            //    Console.WriteLine();
            //    Console.WriteLine();
            //    foreach (int num in ordered)
            //        Console.Write(num + " ");

            //    Console.WriteLine();
            //    Console.WriteLine(lastMax);
            //    Console.WriteLine();
            //}

            return lastMax;
        }