Exemple #1
0
        public override void InitialiseClusters()
        {
            epochCounter = 1;
            iterator     = 1;
            Random Randy = new Random();

            map = new KohonenNeuron[x, y];
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    //randomly initialise weights (in "Centroid" field) of each neuron
                    DenseVector InitialCentroid = new DenseVector(data[0].Item2.Count);
                    Parallel.For(0, InitialCentroid.Count, iter => {
                        InitialCentroid[iter] = Randy.NextDouble();
                    });
                    List <Tuple <string, DenseVector> > EmptyList = new List <Tuple <string, DenseVector> >();
                    map[i, j] = new KohonenNeuron(EmptyList, $"{i}, {j}", new Tuple <int, int>(i, j));
                    map[i, j].SetCentroid(InitialCentroid);
                }
            }
            Tuple <string, DenseVector>[] ShuffleList = new Tuple <string, DenseVector> [data.Count];
            data.CopyTo(ShuffleList);
            shuffleList = ShuffleList.ToList();
        }
Exemple #2
0
        public List <Tuple <double, double> > Fast_forurier_series(List <double> l, int Number)
        {
            if (Number == 2)
            {
                Tuple <double, double>[] out_list = new Tuple <double, double> [Number];
                Tuple <double, double>   t1       = new Tuple <double, double>((l[0] + l[1]), 0.0);
                Tuple <double, double>   t2       = new Tuple <double, double>((l[0] - l[1]), 0.0);

                out_list[0] = t1;
                out_list[1] = t2;
                return(out_list.ToList());
            }

            Tuple <double, double>[] out_list_1 = new Tuple <double, double> [Number];
            List <double>            odd_list   = new List <double>();
            List <double>            even_list  = new List <double>();

            for (int i = 0; i < l.Count; i++)
            {
                if (i % 2 == 0)
                {
                    even_list.Add(l[i]);
                }
                else
                {
                    odd_list.Add(l[i]);
                }
            }

            List <Tuple <double, double> > FFt_odd  = new List <Tuple <double, double> >();
            List <Tuple <double, double> > FFt_even = new List <Tuple <double, double> >();

            int new_N = Number / 2;

            FFt_odd  = Fast_forurier_series(odd_list, new_N);
            FFt_even = Fast_forurier_series(even_list, new_N);

            Tuple <double, double> w;
            double real = 0.0, imagin = 0.0;
            Tuple <double, double> result_sum;
            Tuple <double, double> result_sub;

            for (int k = 0; k <= Number / 2 - 1; k++)
            {
                w          = new Tuple <double, double>(real, imagin);
                w          = calculate_W(k, Number);
                result_sum = new Tuple <double, double>(real, imagin);
                result_sub = new Tuple <double, double>(real, imagin);

                result_sum = Butterfly_up(FFt_even[k], FFt_odd[k], w);
                result_sub = Butterfly_down(FFt_even[k], FFt_odd[k], w);

                out_list_1[k] = result_sum;
                out_list_1[k + Number / 2] = result_sub;
            }
            return(out_list_1.ToList());
        }
        public Skeleton(Tuple<JointType, JointType>[] bones)
        {
            Bones = bones.ToList();

            HashSet<JointType> joints = new HashSet<JointType>();
            foreach (Tuple<JointType, JointType> bone in bones) {
                joints.Add(bone.Item1);
                joints.Add(bone.Item2);
            }
            Joints = joints.ToList();
        }
Exemple #4
0
        public static void Save(string directory, Madingley.Common.Configuration c)
        {
            CreateDirectories(directory);

            var convertTimeSteps = 12;

            var parameters = new Tuple <string, string>[]
            {
                Tuple.Create("Parameter", "Value"),
                Tuple.Create("Timestep Units", c.GlobalModelTimeStepUnit),
                Tuple.Create("Length of simulation (years)", (c.NumTimeSteps / convertTimeSteps).ToString()),
                Tuple.Create("Burn-in (years)", (c.BurninTimeSteps / convertTimeSteps).ToString()),
                Tuple.Create("Impact duration (years)", (c.ImpactTimeSteps / convertTimeSteps).ToString()),
                Tuple.Create("Recovery duration (years)", (c.RecoveryTimeSteps / convertTimeSteps).ToString()),
                Tuple.Create("Plankton size threshold", c.PlanktonDispersalThreshold.ToString()),
                Tuple.Create("Draw Randomly", c.DrawRandomly ? "yes" : "no"),
                Tuple.Create("Extinction Threshold", c.ExtinctionThreshold.ToString()),
                Tuple.Create("Maximum Number Of Cohorts", c.MaxNumberOfCohorts.ToString()),
                Tuple.Create("Run Cells In Parallel", c.RunCellsInParallel ? "yes" : "no"),
                Tuple.Create("Run Simulations In Parallel", c.RunSimulationsInParallel ? "yes" : "no"),
                Tuple.Create("Run Single Realm", c.RunRealm),
                Tuple.Create("Impact Cell Index", System.String.Join(";", c.ImpactCellIndices)),
                // Tuple.Create("ImpactAll", if c.ImpactAll then "yes" else "no"),
                Tuple.Create("Dispersal only", c.DispersalOnly ? "yes" : "no"),
                Tuple.Create("Dispersal only type", c.DispersalOnlyType)
            };

            using (var writer = new StreamWriter(Path.Combine(directory, "SimulationControlParameters.csv")))
            {
                parameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Item1, kv.Item2)));
            }

            var fileLocationParameters = new Tuple <string, string>[]
            {
                Tuple.Create("Parameter", "Value"),
                Tuple.Create("Mass Bin Filename", "MassBinDefinitions.csv"),
                Tuple.Create("Environmental Data File", "EnvironmentalDataLayers.csv"),
                Tuple.Create("Cohort Functional Group Definitions File", "CohortFunctionalGroupDefinitions.csv"),
                Tuple.Create("Stock Functional Group Definitions File", "StockFunctionalGroupDefinitions.csv"),
                Tuple.Create("Ecological parameters file", "EcologicalParameters.csv")
            };

            using (var writer = new StreamWriter(Path.Combine(directory, "FileLocationParameters.csv")))
            {
                fileLocationParameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Item1, kv.Item2)));
            }

            EcologicalParameters.Save(c.EcologicalParameters, Path.Combine(directory, "Ecological Definition Files", "EcologicalParameters.csv"));

            FunctionalGroupDefinitions.Save(c.CohortFunctionalGroupDefinitions, Path.Combine(directory, "Ecological Definition Files", "CohortFunctionalGroupDefinitions.csv"));
            FunctionalGroupDefinitions.Save(c.StockFunctionalGroupDefinitions, Path.Combine(directory, "Ecological Definition Files", "StockFunctionalGroupDefinitions.csv"));

            ScenarioParameters.SaveScenarios(c.ScenarioParameters, Path.Combine(directory, "Initial Model State Setup", "Scenarios.csv"));
        }
 protected List <Tuple <RouteSet, double> > ParallelExeParallelShaking <TProcedure, TParameters>(Exploration expCondition, Random rdObj, List <Func <RouteSet, Exploration, Random, RouteSet> > neighborhoods, List <Func <RouteSet, Random, RouteSet> > shaking, TProcedure procedure, TParameters parameters, RouteSet bestSolution, RouteSet current, int iteration, Stopwatch timer) where TProcedure : LocalSearchProcedure <RouteSet, TParameters>
 {
     Tuple <RouteSet, double>[] parallelSolutions = new Tuple <RouteSet, double> [shaking.Count];
     Parallel.For(0, shaking.Count, i => {
         var shk              = shaking[i](current, rdObj);
         Random prdObj        = new Random((i + 1) * (i + 2) * Environment.TickCount);
         var imp              = procedure.Solve(parameters, shk, neighborhoods, expCondition, GetCost, prdObj);
         parallelSolutions[i] = new Tuple <RouteSet, double>(imp, GetCost(imp));
         OnIteration(new IterationEventArgs <RouteSet>(bestSolution, imp, (iteration + 1) * i, timer.Elapsed.TotalSeconds));/*iteration+1 pq las iteraciones comienzan en cero*/
     });
     return(parallelSolutions.ToList());
 }
Exemple #6
0
        private static void RemoveCandidates(SolvingContext context, ICellGroup cellGroup,
                                             Tuple <ICell, ICell> pair)
        {
            var otherCells  = cellGroup.Except(pair.ToList()).ToList();
            var firstFields = pair.Item1.GetCandidates().ToList();

            context.Pairs.Add(Tuple.Create(firstFields.First(), firstFields.Last()));
            context.PairFound = true;
            foreach (var otherCell in otherCells)
            {
                context.CellsAffectedWithCrossOut += otherCell.RemoveCandidates(firstFields.ToArray());
            }
        }
Exemple #7
0
        public void Ranking(string s)
        {
            //List<Tuple<int, int, int>> sortedL = new List<Tuple<int, int, int>>();
            Tuple <int, int, int>[] L       = new Tuple <int, int, int> [s.Length];
            List <int>[]            ranking = new List <int> [26];
            for (int i = 0; i < s.Length; i++)
            {
                if (ranking[i] == null)
                {
                    ranking[i] = new List <int>(new int[1000000]);
                }
                ranking[0][i] = s[i] - 'a';
            }

            for (int cnt = 1, stp = 1; cnt < s.Length; cnt *= 2, stp++)
            {
                for (int i = 0; i < s.Length; i++)
                {
                    int ans = -1;
                    if (i + cnt < s.Length)
                    {
                        ans = ranking[stp - 1][i + cnt];
                    }

                    L[i] = Tuple.Create(i,
                                        ranking[stp - 1][i],
                                        ans);
                }

                Array.Sort(L, cmp);
                //sortedL = L.ToList();
                //sortedL.Sort(cmp);
                // Initialize rank for rank 0 suffix after sorting to its original index
                // in suffixRank array
                ranking[stp][L[0].Item1] = 0;

                for (int j = 1, currRank = 0; j < s.Length; j++)
                {
                    if (L[j - 1].Item2 != L[j].Item2 || L[j - 1].Item3 != L[j].Item3)
                    {
                        ++currRank;
                    }

                    int ind = L[j].Item1;
                    ranking[stp][ind] = currRank;
                }
            }

            this.myTuple = L.ToList();
        }
Exemple #8
0
        /// <summary>
        /// Create a copy of the object. This object should not have any
        /// reference to the original and should be save to alter.
        /// </summary>
        /// <returns>The copy</returns>
        public IShape Clone()
        {
            var coordinates = new Tuple <int, int> [this.Coordinates.Count];

            this.Coordinates.CopyTo(coordinates);

            return(new Polygon()
            {
                Red = this.Red,
                Green = this.Green,
                Blue = this.Blue,
                Alpha = this.Alpha,
                Coordinates = coordinates.ToList()
            });
        }
Exemple #9
0
        private List <Tuple <RouteSet, double> > ParallelExeDualParallelShaking <TProcedure, TParameters>(Exploration expCondition, Random rdObj, List <Func <RouteSet, Exploration, Random, RouteSet> > neighborhoods, List <Func <RouteSet, Random, RouteSet> > shaking, TProcedure procedure, TParameters parameters, RouteSet bestSolution, RouteSet current, int iteration, Stopwatch timer, double[,] dualCost) where TProcedure : LocalSearchProcedure <RouteSet, TParameters>
        {
            Tuple <RouteSet, double>[]    parallelSolutions = new Tuple <RouteSet, double> [shaking.Count];
            VRPSimultaneousPickupDelivery dualProblem       = ProblemData.GetDualReduceCostProblem(dualCost);
            PenalizationLocalSearch       dualProcedure     = new PenalizationLocalSearch(dualProblem);

            dualProcedure.OverloadFactor = OverloadFactor;

            Parallel.For(0, shaking.Count, i => {
                Random pRdObj        = new Random((i + 1) * (i + 2) * Environment.TickCount);
                var shk              = shaking[i](current, pRdObj);
                var imp              = procedure.Solve(parameters, shk, neighborhoods, expCondition, dualProcedure.GetCost, pRdObj); /*para la construccion de las nuevas rutas se usan los costos reducidos*/
                parallelSolutions[i] = new Tuple <RouteSet, double>(imp, GetCost(imp));
                OnIteration(new IterationEventArgs <RouteSet>(bestSolution, imp, (iteration + 1) * i, timer.Elapsed.TotalSeconds));  /*iteration+1 pq las iteraciones comienzan en cero*/
            });

            return(parallelSolutions.ToList());
        }
        public void TupleToListTest()
        {
            // Arrange
            float v1 = 0.2342523523523452345F;
            float v2 = 0.2342523523523452345F;
            float v3 = 0.2342523523523452345F;

            var tuple = new Tuple <float, float, float>(v1, v2, v3);

            // Act
            var tupleToList = tuple.ToList();

            // Assert
            Assert.AreNotEqual(0, tupleToList.Count);
            Assert.AreEqual(3, tupleToList.Count);
            Assert.AreEqual(typeof(List <float>), tupleToList.GetType());
            Assert.AreEqual(true, tupleToList.Contains(v1));
            Assert.AreEqual(true, tupleToList.Contains(v2));
            Assert.AreEqual(true, tupleToList.Contains(v3));
            Console.WriteLine("Result of converting tuple to a List<float> name tupleToList: {0}", tupleToList);
        }
Exemple #11
0
/*
        public static IAssemblySymbol[] GetReferencedAssemblies(IAssemblySymbol assembly)
        {
            var result = assembly.GetType().GetMethod("GetLinkedReferencedAssemblies", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(assembly, new object[0]);
            if (result == null)
                return new IAssemblySymbol[0];
            return result.ToArray();
        }
*/

        public static IAssemblySymbol[] Sort(Tuple<IAssemblySymbol, IAssemblySymbol[]>[] assemblies)
        {
            var currentList = assemblies.ToList();

            var prepend = new HashSet<Tuple<IAssemblySymbol, IAssemblySymbol[]>>();
            do 
            {
                prepend.Clear();
                var indices = currentList.Select((x, i) => new { Item = x, Index = i }).ToDictionary(x => x.Item.Item1, x => x.Index);
                for (var i = 0; i < currentList.Count; i++)
                {
                    var item = currentList[i];
                    foreach (var referencedAssembly in item.Item2)
                    {
                        int assemblyIndex;
                        if (indices.TryGetValue(referencedAssembly, out assemblyIndex))
                        {
                            if (assemblyIndex > i)
                            {
                                var referencedAssemblyItem = currentList[assemblyIndex];
                                prepend.Add(referencedAssemblyItem);
                            }
                        }                        
                    }
                }
                if (prepend.Any())
                {
                    var newItems = prepend.Concat(currentList.Where(x => !prepend.Contains(x))).ToArray();
                    currentList.Clear();
                    currentList.AddRange(newItems);
                }
            }
            while (prepend.Any());

            return currentList.Select(x => x.Item1).ToArray();
        }
Exemple #12
0
        public Tuple <int, double>[] top_k(int k)
        {
            // Kopieer scores naar een nieuwe dictionary van lijsten, die we sorteren
            var gesorteerd = new Dictionary <string, List <Tuple <int, double> > >();

            foreach (string a in zoek_attributen)
            {
                var b = new Tuple <int, double> [N];
                attr_scores[a].CopyTo(b);
                gesorteerd[a] = b.ToList();
                gesorteerd[a].Sort((x, y) => y.Item2.CompareTo(x.Item2));
            }

            Dictionary <int, double>    buffer = new Dictionary <int, double>();
            Dictionary <string, double> max    = new Dictionary <string, double>(gesorteerd.Count);
            List <Tuple <int, double> > top    = new List <Tuple <int, double> >(k);
            double drempel;

            HashSet <int> gezien = new HashSet <int>();
            int           r      = 0;

            while (top.Count < k && r < N)
            {
                drempel = 0;
                // Elke ronde elke attribuut een stap verder
                foreach (var a in zoek_attributen)
                {
                    // De maximale score (som van attr.) die nog behaald kan worden
                    // Alles wat we vinden dat hierboven zit, gaat in de top-k
                    var    lijst    = gesorteerd[a];
                    double bovenste = lijst[r].Item2;
                    max[a]   = bovenste;
                    drempel += bovenste;

                    int tid = lijst[r].Item1;

                    // Als we een nieuwe tupel vinden, bereken we de score van de gehele tupel
                    if (!gezien.Contains(tid))
                    {
                        gezien.Add(tid);
                        double score = 0;
                        foreach (var b in zoek_attributen)
                        {
                            score += attr_scores[b][tid - 1].Item2; // Lijst[0] heeft tupel id = 1
                        }
                        buffer.Add(tid, score);
                    }
                }

                List <int> te_verwijderen = new List <int>();

                foreach (var kandidaat in buffer.Keys)
                {
                    if (buffer[kandidaat] >= drempel)
                    {
                        top.Add(Tuple.Create(kandidaat, buffer[kandidaat]));
                        te_verwijderen.Add(kandidaat);
                    }
                }

                foreach (var s in te_verwijderen)
                {
                    buffer.Remove(s);
                }

                r++;
            }

            top.Sort((x, y) => y.Item2.CompareTo(x.Item2));

            Tuple <int, double>[] res = new Tuple <int, double> [k];
            for (int i = 0; i < k; i++)
            {
                res[i] = top[i];
            }

            return(res);
        }
        public static void Save(string directory, Madingley.Common.Configuration c)
        {
            CreateDirectories(directory);

            var convertTimeSteps = 12;

            var parameters = new Tuple<string, string>[]
                {
                    Tuple.Create("Parameter", "Value"),
                    Tuple.Create("Timestep Units", c.GlobalModelTimeStepUnit),
                    Tuple.Create("Length of simulation (years)", (c.NumTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Burn-in (years)", (c.BurninTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Impact duration (years)", (c.ImpactTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Recovery duration (years)", (c.RecoveryTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Plankton size threshold", c.PlanktonDispersalThreshold.ToString()),
                    Tuple.Create("Draw Randomly", c.DrawRandomly ? "yes" : "no"),
                    Tuple.Create("Extinction Threshold", c.ExtinctionThreshold.ToString()),
                    Tuple.Create("Maximum Number Of Cohorts", c.MaxNumberOfCohorts.ToString()),
                    Tuple.Create("Run Cells In Parallel", c.RunCellsInParallel ? "yes" : "no"),
                    Tuple.Create("Run Simulations In Parallel", c.RunSimulationsInParallel ? "yes" : "no"),
                    Tuple.Create("Run Single Realm", c.RunRealm),
                    Tuple.Create("Impact Cell Index", System.String.Join(";", c.ImpactCellIndices)),
                    // Tuple.Create("ImpactAll", if c.ImpactAll then "yes" else "no"),
                    Tuple.Create("Dispersal only", c.DispersalOnly ? "yes" : "no"),
                    Tuple.Create("Dispersal only type", c.DispersalOnlyType)
                };

            using (var writer = new StreamWriter(Path.Combine(directory, "SimulationControlParameters.csv")))
            {
                parameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Item1, kv.Item2)));
            }

            var fileLocationParameters = new Tuple<string, string>[]
                {
                    Tuple.Create("Parameter", "Value"),
                    Tuple.Create("Mass Bin Filename", "MassBinDefinitions.csv"),
                    Tuple.Create("Environmental Data File", "EnvironmentalDataLayers.csv"),
                    Tuple.Create("Cohort Functional Group Definitions File", "CohortFunctionalGroupDefinitions.csv"),
                    Tuple.Create("Stock Functional Group Definitions File", "StockFunctionalGroupDefinitions.csv"),
                    Tuple.Create("Ecological parameters file","EcologicalParameters.csv")
                };

            using (var writer = new StreamWriter(Path.Combine(directory, "FileLocationParameters.csv")))
            {
                fileLocationParameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Item1, kv.Item2)));
            }

            EcologicalParameters.Save(c.EcologicalParameters, Path.Combine(directory, "Ecological Definition Files", "EcologicalParameters.csv"));

            FunctionalGroupDefinitions.Save(c.CohortFunctionalGroupDefinitions, Path.Combine(directory, "Ecological Definition Files", "CohortFunctionalGroupDefinitions.csv"));
            FunctionalGroupDefinitions.Save(c.StockFunctionalGroupDefinitions, Path.Combine(directory, "Ecological Definition Files", "StockFunctionalGroupDefinitions.csv"));

            ScenarioParameters.SaveScenarios(c.ScenarioParameters, Path.Combine(directory, "Initial Model State Setup", "Scenarios.csv"));
        }
Exemple #14
0
        /// <summary>
        /// Построение дерева Штейнера полным перебором
        /// </summary>
        /// <param name="points"> Список вершин графа </param>
        /// <returns> Список рёбер </returns>
        public static dynamic Solve(List <T> points)
        {
            if (points.Count < 2)
            {
                return(null);
            }

            /*********************************************************************************/
            /* 1) Необходимо построить сеточный граф на основе исходных точек                */
            /* 2) Затем вызвать полный перебор всех решений, т.е. перебирать                 */
            /*    все возможные комбинации рёбер                                             */
            /* Количество рёбер рассматриваемых для решения урезано до половины от сеточного */
            /* графа, т.к. "дорога", длинной больше этой, точно не будет оптимальной         */
            /*********************************************************************************/

            List <double> x_list = new List <double>();
            List <double> y_list = new List <double>();

            for (int i = 0; i < points.Count; i++)
            {
                x_list.Add(points[i].X);
                y_list.Add(points[i].Y);
            }
            x_list.Sort();
            y_list.Sort();
            x_list = x_list.Distinct().ToList();
            y_list = y_list.Distinct().ToList();

            int width  = x_list.Count - 1;
            int height = y_list.Count - 1;

            // количество рёбер = сумма чётностей вершин пополам
            int countEdges = (4 * 2 + 2 * 3 * (height - 1) + 2 * 3 * (width - 1) + 4 * (height - 1) * (width - 1)) / 2;

            // заполняем массивы длин рёбер и пар точек
            double[] lens           = new double[countEdges];
            var      pairs_of_verts = new Tuple <T, T> [countEdges];

            for (int i = 0; i <= height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    lens[i * width + i * (width + 1) + j]           = x_list[j + 1] - x_list[j];
                    pairs_of_verts[i * width + i * (width + 1) + j] = new Tuple <T, T>(new Point2D(x_list[j], y_list[i]) as T, new Point2D(x_list[j + 1], y_list[i]) as T);
                }
            }
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j <= width; j++)
                {
                    lens[(i + 1) * width + i * (width + 1) + j]           = y_list[i + 1] - y_list[i];
                    pairs_of_verts[(i + 1) * width + i * (width + 1) + j] = new Tuple <T, T>(new Point2D(x_list[j], y_list[i]) as T, new Point2D(x_list[j], y_list[i + 1]) as T);
                }
            }

            // вырожденный случай, когда все точки находятся на одной линии
            if (x_list.Count == 1 || y_list.Count == 1)
            {
                return(pairs_of_verts.ToList());
            }

            int[] x = new int[countEdges];
            // решаем полным перебором
            int[] solution = BruteIter(x, 0, lens, pairs_of_verts.ToList(), points);

            // сохраняем пары вершин (рёбра), которые входят в решение
            var solution_edges = new List <Tuple <T, T> >();

            for (int i = 0; i < solution.Length; i++)
            {
                if (solution[i] == 1)
                {
                    solution_edges.Add(pairs_of_verts[i]);
                }
            }

            return(solution_edges);
        }
Exemple #15
0
        /*
        Problem Statement
        Two armies composed of magical creatures are facing off at a battlefield. To provide a more epic feel to the battle, the armies have agreed that each creature will attack exactly once and that only one creature may attack at a time.

        Each creature has a might trait assigned to it. The order in which the creatures attack is uniquely determined by the following rules:

        Creatures with higher might attack before creatures with lower might.
        If creatures have equal might, attacking creatures alternate between armies. For example, if the last creature to attack was from the first army and the next creature could be from either army, a creature from the second army will attack next. If the very first attack is to be decided, a creature from the first army goes first.
        If more than one creature in the same army has the same might, the creature given earlier in the input goes first.
        You will be given the descriptions of the armies as two s, army1 and army2. Each element of army1 and army2 will be formatted as "NAME MIGHT" (quotes for clarity), where NAME is the name of a creature, and MIGHT is an integer, the might of that creature. Return a containing the creatures' names in the order in which they attack.

        Definition
        Class: Armies
        Method: findOrder
        Parameters: string[], string[]
        Returns: string[]
        Method signature: string[] findOrder(string[] army1, string[] army2)
        (be sure your method is public)
        Limits
        Time limit (s): 840.000
        Memory limit (MB): 64
        Constraints
        - army1 and army2 will each contain between 0 and 50 elements, inclusive.
        - Each element of army1 and army2 will be formatted as "NAME MIGHT" (quotes for clarity).
        - NAME in each element of army1 and army2 will be a string containing between 1 and 20 uppercase letters ('A'-'Z'), inclusive.
        - MIGHT in each element of army1 and army2 will be an integer between 1 and 999, inclusive, without leading zeroes.
        - No two creatures will have the same name.
        Examples
        0)
        { "DRAGON 10" }
        { "BOAR 1", "ELF 3" }
        Returns: {"DRAGON", "ELF", "BOAR" }
        The dragon is by far the mightiest and attacks first. The elf follows and the boar goes last.
        1)
        { "SWORDSMAN 5", "ARCHER 3" }
        { "CENTAUR 2", "ELF 3" }
        Returns: {"SWORDSMAN", "ELF", "ARCHER", "CENTAUR" }
        The swordsman attacks first. The next creature could be either the archer or the elf because both have might 3. Since the first creature to attack was from the first army, the next will be the elf from the second army. The archer and centaur follow.
        2)
        { "ARCHER 5", "PIXIE 3" }
        { "OGRE 10", "WOLF 10", "GOBLIN 3" }
        Returns: {"OGRE", "WOLF", "ARCHER", "GOBLIN", "PIXIE" }
        3)
        { "A 6", "B 7" }
        { }
        Returns: {"B", "A" }
        This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
        */
        public string[] findOrder(string[] army1, string[] army2)
        {
            Tuple<string, int>[] a1 = new Tuple<string, int>[army1.Length];

            for (int i = 0; i < army1.Length; i++)
            {
                string[] a2 = army1[i].Split(' ');
                a1[i] = new Tuple<string, int>(a2[0], int.Parse(a2[1]));
            }

            Tuple<string, int>[] b1 = new Tuple<string, int>[army2.Length];

            for (int i = 0; i < army2.Length; i++)
            {
                string[] b2 = army2[i].Split(' ');
                b1[i] = new Tuple<string, int>(b2[0], int.Parse(b2[1]));
            }

            List<Tuple<string, int>> a3 = a1.ToList();
            List<Tuple<string, int>> a4 = new List<Tuple<string, int>>();
            for (int i = 0; i < a3.Count - 1; i++)
            {
                if (a3[i].Item2 < a3[i + 1].Item2)
                {
                    Tuple<string, int> temp = a3[i + 1];
                    a3[i + 1] = a3[i];
                    a3[i] = temp;
                }
            }
            a1 = a3.ToArray();

            List<Tuple<string, int>> b3 = b1.ToList();
            List<Tuple<string, int>> b4 = new List<Tuple<string, int>>();
            for (int i = 0; i < b3.Count - 1; i++)
            {
                if (b3[i].Item2 < b3[i + 1].Item2)
                {
                    Tuple<string, int> temp = b3[i + 1];
                    b3[i + 1] = b3[i];
                    b3[i] = temp;
                }
            }
            b1 = b3.ToArray();

            string[] result = new string[b1.Length + a1.Length];
            int lastAtk = 0;
            int acounter = 0;
            int bcounter = 0;
            for (int i = 0; i < result.Length; i++)
            {
                if (a1.Length > i - acounter)
                {
                    if (b1.Length > i - bcounter)
                    {
                        if (a1[i - acounter].Item2 == b1[i - bcounter].Item2)
                        {
                            if (lastAtk == 1)
                            {
                                result[i] = a1[i - acounter].Item1;
                                bcounter++;
                                lastAtk = 0;
                            }
                            else
                            {
                                result[i] = b1[i - bcounter].Item1;
                                acounter++;
                                lastAtk = 1;
                            }
                        }
                        else if (a1[i - acounter].Item2 > b1[i - bcounter].Item2)
                        {
                            result[i] = a1[i - acounter].Item1;
                            bcounter++;
                            lastAtk = 0;
                        }
                        else
                        {
                            result[i] = b1[i - bcounter].Item1;
                            acounter++;
                            lastAtk = 1;
                        }
                    }
                    else
                    {
                        result[i] = a1[i - acounter].Item1;
                        bcounter++;
                        lastAtk = 0;
                    }
                }
                else
                {
                    result[i] = b1[i - bcounter].Item1;
                    acounter++;
                    lastAtk = 1;
                }

            }
            return result;
        }
Exemple #16
0
        /// <summary>
        /// Построение дерева Штейнера муравьиным алгоритмом
        /// </summary>
        /// <param name="points"> Список вершин графа </param>
        /// <returns> Список рёбер </returns>
        public static dynamic Solve(List <T> points)
        {
            if (points.Count < 2)
            {
                return(null);
            }

            List <double> x_list = new List <double>();
            List <double> y_list = new List <double>();

            for (int i = 0; i < points.Count; i++)
            {
                x_list.Add(points[i].X);
                y_list.Add(points[i].Y);
            }
            x_list.Sort();
            y_list.Sort();
            x_list = x_list.Distinct().ToList();
            y_list = y_list.Distinct().ToList();

            int width  = x_list.Count - 1;
            int height = y_list.Count - 1;

            // количество рёбер = сумма чётностей вершин пополам
            int countEdges = (4 * 2 + 2 * 3 * (height - 1) + 2 * 3 * (width - 1) + 4 * (height - 1) * (width - 1)) / 2;

            // заполняем массивы длин рёбер и пар точек
            double[] lens           = new double[countEdges];
            var      pairs_of_verts = new Tuple <T, T> [countEdges];

            for (int i = 0; i <= height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    lens[i * width + i * (width + 1) + j]           = x_list[j + 1] - x_list[j];
                    pairs_of_verts[i * width + i * (width + 1) + j] = new Tuple <T, T>(new Point2D(x_list[j], y_list[i]) as T, new Point2D(x_list[j + 1], y_list[i]) as T);
                }
            }
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j <= width; j++)
                {
                    lens[(i + 1) * width + i * (width + 1) + j]           = y_list[i + 1] - y_list[i];
                    pairs_of_verts[(i + 1) * width + i * (width + 1) + j] = new Tuple <T, T>(new Point2D(x_list[j], y_list[i]) as T, new Point2D(x_list[j], y_list[i + 1]) as T);
                }
            }

            // вырожденный случай, когда все точки находятся на одной линии
            if (x_list.Count == 1 || y_list.Count == 1)
            {
                return(pairs_of_verts.ToList());
            }

            /***********************************************************************************************/
            /* Изначально имеем набор рёбер сетки с равными вероятностями взятия                           */
            /* 1) Выбираем случайно рёбра сетки, пока не получится связное дерево                          */
            /* 2) Сохраняем его и проделываем с этим же набором вероятностей ещё несколько таких итераций  */
            /* 3) Выбираем из них лучшее (по значению критерия) и корректируем вероятности выпадения       */
            /* 4) Проделываем шаги (1)-(3) для этих вероятностей выпадения, и т.д до какого-то останова    */
            /***********************************************************************************************/

            int stop_iterations        = 30; // количество итераций обучения мураьиного алгоритма
            int current_iteration      = 0;  // текущее количество итераций
            int max_count_of_roads     = 2;  // количество сохраняемых решений на каждой итерации
            int current_count_of_roads = 0;  // текущее количество сохранённых решений


            // будем сохранять лучшие решения и их списки вероятностей рёбер
            var save_solutions = new List <Tuple <int[], List <int> > >();

            // лист вероятностей (лежат номера вершин)
            var list_propapility = new List <int>();

            for (int i = 0; i < countEdges; i++)
            {
                list_propapility.Add(i);
            }

            // сохраняем первый набор "вероятностей"
            save_solutions.Add(new Tuple <int[], List <int> >(new List <int>(new int[countEdges]).ToArray(), new List <int>(list_propapility)));

            // запускаем установленное число итераций "обучения" алгоритма
            while (current_iteration < stop_iterations)
            {
                var list_solutions = new List <int[]>(); // список для сохранения решений
                current_count_of_roads = 0;              // обнуляем счётчик сохранённых решений
                // находим установленное число решений в одном "поколении обучения"
                while (current_count_of_roads < max_count_of_roads)
                {
                    int[] x_temp         = new int[countEdges];
                    var   temp_prob_list = new List <int>(save_solutions.Last().Item2);
                    int   sas            = 0;
                    do
                    {
                        sas++;
                        x_temp         = new int[countEdges];
                        temp_prob_list = new List <int>(save_solutions.Last().Item2);
                        int random_choices = Rand.rand.Next(points.Count - 1, countEdges / 2 + 1); // количество слуйно выбираемых рёбер
                        int rand_edge;
                        while (random_choices > 0)
                        {
                            rand_edge = temp_prob_list[Rand.rand.Next(0, temp_prob_list.Count)]; // рандомим номер ребра
                            temp_prob_list.RemoveAll(num => num == rand_edge);                   // удаляем все номера, равные выпавшему (т.к. уже взяли его)
                            x_temp[rand_edge] = 1;                                               // берём это ребро
                            random_choices--;
                        }
                    }while (!Check(x_temp, pairs_of_verts.ToList(), points)); // пока не получим связное дерево, рандомим
                    // удаляем лишние рёбра
                    x_temp = DeleteExcessEdges(x_temp, pairs_of_verts.ToList(), points);

                    list_solutions.Add(new List <int>(x_temp).ToArray()); // сохраняем это решение
                    current_count_of_roads++;
                }

                // сохраняем лучшее из полученных решений
                int[]  best_solution = new int[countEdges];
                double min_q         = double.MaxValue;
                for (int i = 0; i < list_solutions.Count; i++)
                {
                    double q = Q(list_solutions[i], lens);
                    if (q < min_q)
                    {
                        min_q = q;
                        list_solutions[i].CopyTo(best_solution, 0);
                    }
                }
                // обновляем вероятности
                var prob_list = new List <int>(save_solutions.Last().Item2);
                for (int i = 0; i < best_solution.Length; i++)
                {
                    if (best_solution[i] == 1)
                    {
                        prob_list.Insert(Rand.rand.Next(0, prob_list.Count), i);
                    }
                }
                // сохраняем лучшее решение и вероятности
                save_solutions.Add(new Tuple <int[], List <int> >(new List <int>(best_solution).ToArray(), new List <int>(prob_list)));
                current_iteration++;
            }

            // удаляем первое (пустое) решение
            save_solutions.RemoveAt(0);

            // выбираем минимальное из полученных решений среди всех итераций
            double min     = double.MaxValue;
            int    min_ind = 0;

            for (int i = 0; i < save_solutions.Count; i++)
            {
                double q = Q(save_solutions[i].Item1, lens);
                if (q < min)
                {
                    min     = q;
                    min_ind = i;
                }
            }

            // записываем решение в виде рёбер
            var solution_edges = new List <Tuple <T, T> >();

            for (int i = 0; i < save_solutions[min_ind].Item1.Length; i++)
            {
                if (save_solutions[min_ind].Item1[i] == 1)
                {
                    solution_edges.Add(pairs_of_verts[i]);
                }
            }

            return(solution_edges);
        }
                private static List<Chain> GetChains(Tuple<int, int>[] segments)
                {
                    // Find the points that have more than two segments pointing to them
                    var pointCounts = UtilityCore.Iterate(segments.Select(o => o.Item1), segments.Select(o => o.Item2)).
                        GroupBy(o => o).
                        Select(o => Tuple.Create(o.Key, o.Count())).
                        Where(o => o.Item2 > 2).
                        ToArray();

                    List<Tuple<int, int>> segmentList = segments.ToList();

                    if (pointCounts.Length == 0)
                    {
                        // There are no junctions, so just return the unique loops
                        return GetChainsSprtLoops(segmentList);
                    }

                    List<Chain> retVal = new List<Chain>();

                    retVal.AddRange(GetChainsSprtFragments(segmentList, pointCounts));

                    if (segmentList.Count > 0)
                    {
                        retVal.AddRange(GetChainsSprtLoops(segmentList));
                    }

                    return retVal;
                }
Exemple #18
0
        public override void IterateOnce()
        {
            if (!stopped)
            {
                if (Decimal.Divide(Decimal.Divide(iterator, epochCounter), data.Count) == 1)
                {
                    //maintaining separate list allows sampling without replacement at random throughout each epoch
                    //of training.  This needs to be reset to match all data at start of each epoch.
                    // 1 epoch = 1 pass over all datapoints

                    epochCounter++;
                    Tuple <string, DenseVector>[] ShuffleList = new Tuple <string, DenseVector> [data.Count];
                    data.CopyTo(ShuffleList);
                    shuffleList = ShuffleList.ToList();
                }
                //randomly select datapoint with replacement
                Random CurrentRand = new Random();
                int    PickIndex   = CurrentRand.Next(shuffleList.Count);
                Tuple <string, DenseVector> Picked = shuffleList[PickIndex];
                shuffleList.RemoveAt(PickIndex);
                //select most appropriate neuron by distance (distance squared to reduce overhead)
                double           BestDistance   = HelperFunctions.GetEuclideanDistanceSquared(Picked.Item2, map[0, 0].GetCentroid());
                Tuple <int, int> BestCoordinate = new Tuple <int, int>(0, 0);
                KohonenNeuron    Best           = map[0, 0];
                for (int i = 1; i < x; i++)
                {
                    Parallel.For(0, y, j =>
                    {
                        double TestDistance = HelperFunctions.GetEuclideanDistanceSquared(Picked.Item2, map[i, j].GetCentroid());
                        if (BestDistance > TestDistance)
                        {
                            BestDistance   = TestDistance;
                            BestCoordinate = new Tuple <int, int>(i, j);
                            Best           = map[i, j];
                        }
                    });
                }
                //update data coordinates list
                currentDataCoordinates[data.IndexOf(Picked)] = BestCoordinate;
                //select neighbourhood and adjust neighbours' weights accordingly
                //exponential decay formula ensures neighbourhood keeps shrinking
                double CurrentRadius       = radius * Math.Exp(-(double)Decimal.Divide(iterator, (decimal)timeConstant));
                double CurrentLearningRate = learningRate * Math.Exp(-(double)Decimal.Divide(iterator, (decimal)timeConstant));
                for (int i = 0; i < x; i++)
                {
                    Parallel.For(0, y, j =>
                    {
                        double DistanceFromBest = HelperFunctions.GetEuclideanDistanceSquared(Best.Coordinates, map[i, j].Coordinates);
                        if (DistanceFromBest < Math.Pow(CurrentRadius, 2))
                        {
                            double NeighbourhoodWeighting   = Math.Exp(-(double)Decimal.Divide((decimal)DistanceFromBest, (decimal)(2 * Math.Pow(CurrentRadius, 2))));
                            DenseVector CentroidReplacement = map[i, j].GetCentroid() + (NeighbourhoodWeighting * CurrentLearningRate) * (Picked.Item2 - map[i, j].GetCentroid());
                            map[i, j].SetCentroid(CentroidReplacement);
                        }
                    });
                }
                //housekeeping
                iterator++;
                stopped = StoppingConditionMet();
                if (stopped)
                {
                    //add all datapoints to clusters by coordinates
                    //add all neurons to cluster list
                    for (int i = 0; i < x; i++)
                    {
                        for (int j = 0; j < y; j++)
                        {
                            ConcurrentBag <Tuple <string, DenseVector> > FinalMemberList = new ConcurrentBag <Tuple <string, DenseVector> >();
                            Parallel.For(0, data.Count, datum =>
                            {
                                if (currentDataCoordinates[datum].Item1 == map[i, j].Coordinates[0] && currentDataCoordinates[datum].Item2 == map[i, j].Coordinates[1])
                                {
                                    FinalMemberList.Add(data[datum]);
                                }
                            });
                            map[i, j].AddMembers(FinalMemberList.OrderBy(o => o.Item1).ToList());
                            clusters.Add(map[i, j]);
                        }
                    }
                }
            }
        }
Exemple #19
0
        public List <Plant> GenerateChildPopulation(List <Plant> parents)
        {
            //Dictionary<ILSystem, float> fitnessPerParent = new Dictionary<ILSystem, float>(parents.Count);
            Tuple <ILSystem, float>[] fitnessPerParent = new Tuple <ILSystem, float> [parents.Count];

            var threads = new List <Thread>();

            for (int i = 0; i < parents.Count; ++i)
            {
                threads.Add(new Thread(x =>
                {
                    object[] threadInput = (object[])x;
                    int index            = (int)threadInput[0];
                    Tuple <ILSystem, float>[] tupleList = (Tuple <ILSystem, float>[])threadInput[1];
                    Plant parentPlant             = (Plant)threadInput[2];
                    PlantFitness fitnessEvaluator = new PlantFitness(new LeafFitness(_sunInformation));
                    float fitness    = fitnessEvaluator.EvaluateFitness(parentPlant);
                    tupleList[index] = new Tuple <ILSystem, float>(parentPlant.LindenMayerSystem, fitness);
                }));
                threads[threads.Count - 1].Start(new object[] { i, fitnessPerParent, parents[i] });

                //float fitness = _fitness.EvaluateFitness(parents[i]);
                //fitnessPerParent[i] = new Tuple<ILSystem, float>(parents[i].LindenMayerSystem, fitness);
            }
            foreach (var thread in threads)
            {
                thread.Join();
            }

            List <List <ILSystem> > parentPairs = _selection.SelectParentPairs(fitnessPerParent.ToList(), 50);

            Plant[] childPlants = new Plant[parentPairs.Count];
            threads.Clear();
            for (int i = 0; i < parentPairs.Count; ++i)
            {
                threads.Add(new Thread(x =>
                {
                    object[] threadInput              = (object[])x;
                    int index                         = (int)threadInput[0];
                    Plant[] childPlantList            = (Plant[])threadInput[1];
                    List <ILSystem> currentParentPair = (List <ILSystem>)threadInput[2];
                    //RuleSet childRuleSet = _crossOver.CrossOver(parentPair[0].GetRuleSet(), parentPair[1].GetRuleSet());
                    //RuleSet childRuleSet = _crossOver.CrossOverV2(parentPairs[i][0].GetRuleSet(), parentPairs[i][1].GetRuleSet());
                    PlantCrossOver crossOver = new PlantCrossOver(new Random());
                    PlantMutation mutation   = new PlantMutation(new Random(), _mutationChance);
                    //RuleSet childRuleSet = crossOver.CrossOver(currentParentPair[0].GetRuleSet(), currentParentPair[1].GetRuleSet());
                    Color newLeafColour   = crossOver.CrossOverLeafColour(currentParentPair[0].GetLeafColor(), currentParentPair[1].GetLeafColor());
                    RuleSet childRuleSet  = crossOver.CrossOverV2(currentParentPair[0].GetRuleSet(), currentParentPair[1].GetRuleSet());
                    childRuleSet          = mutation.Mutate(childRuleSet, ref newLeafColour);
                    childPlantList[index] = new Plant(new LSystem(childRuleSet, "A"), _turtlePen, new PersistentPlantGeometryStorage(), Vector3.zero, newLeafColour);
                }));
                threads[threads.Count - 1].Start(new object[] { i, childPlants, parentPairs[i] });

                //Color newLeafColour = _crossOver.CrossOverLeafColour(parentPairs[i][0].GetLeafColor(), parentPairs[i][1].GetLeafColor());
                //RuleSet childRuleSet = _crossOver.CrossOverV2(parentPairs[i][0].GetRuleSet(), parentPairs[i][1].GetRuleSet());
                //childRuleSet = _mutation.Mutate(childRuleSet, ref newLeafColour);
                //childPlants[i] = new Plant(new LSystem(childRuleSet, "A"), _turtlePen, new PersistentPlantGeometryStorage(), Vector3.zero, newLeafColour);
            }
            foreach (var thread in threads)
            {
                thread.Join();
            }

            return(childPlants.ToList());
        }
Exemple #20
0
 public static IEnumerable <T> ToEnumerable <T>(this Tuple <T, T, T, T, T, T, T> tuple)
 {
     return(tuple.ToList());
 }
Exemple #21
0
 public static IReadOnlyCollection <T> ToReadOnlyCollection <T>(
     this Tuple <T, T, T, T, T, T, T> tuple)
 {
     return(tuple.ToList());
 }
Exemple #22
0
 public static IReadOnlyList <T> ToReadOnlyList <T>(this Tuple <T, T> tuple)
 {
     return(tuple.ToList());
 }