private static void Main(string[] args)
    {
        string[] strings = new string[int.Parse(Console.ReadLine())];
        for (int i = 0; i < strings.Length; i++)
        {
            strings[i] = Console.ReadLine();
        }

        Dictionary<string, int> Areas = new Dictionary<string, int>();

        foreach (var item in strings)
        {
            if (Areas.ContainsKey(item))
            {
                Areas[item]++;
            }
            else
            {
                Areas.Add(item, 1);
            }
        }

        for (int i = 0; i < Areas.Max(x => x.Value); i++)
        {
            Console.WriteLine(Areas.Aggregate((x, y) => y.Value > x.Value ? y : x).Key);
        }
    }
        public static void Main()
        {
            List<int> numbers = new List<int>() { 3, 4, 4, 2, 3, 3, 3, 3, 3, 2, 5, 3, 5, 6, 3, 5, 3 };
            Dictionary<int, int> occures = new Dictionary<int, int>();
            foreach (var item in numbers)
            {
                if (occures.ContainsKey(item))
                {
                    occures[item]++;
                }
                else
                {
                    occures.Add(item, 1);
                }
            }

            int maxOccures = occures.Max(x => x.Value);
            int countAllElements = numbers.Count;
            if (maxOccures >= countAllElements / 2 + 1)
            {
                Console.WriteLine("majorant is: {0}", maxOccures);
            }
            else
            {
                Console.WriteLine("majorant not exist");
            }
        }
        public static string GetBestDays(int suggestionId)
        {
            List<JoinedUser> users = GetJoinedUsers(suggestionId);

            Dictionary<String, int> votesPerDay = new Dictionary<string, int>();

            foreach (var user in users)
            {
                String[] days = user.Weekdays.Split(',');
                foreach (var day in days)
                {
                    int count;
                    if (votesPerDay.TryGetValue(day, out count))
                        votesPerDay[day] = count + 1;
                    else
                        votesPerDay.Add(day, 1);
                }
            }

            int highest = votesPerDay.Max(kvp => kvp.Value);
            var values = "";

            foreach (var kvp in votesPerDay)
            {
                if (kvp.Value == highest)
                    values += kvp.Key + ", ";
            }

            if (values.Length >= 2)
                values = values.Remove(values.Length - 2, 2);

            return values;
        }
        public void VisaData(IList<AktivPeriod> perioder)
        {
            panel1.Controls.Clear();

            var lista = new Dictionary<DateTime, double>();

            foreach (var dag in perioder.Select(o => o.Starttid.Date).Distinct())
            {
                var summeradDag = dag;
                lista.Add(dag,
                          perioder.Where(o => o.Starttid.Date.Equals(summeradDag)).Sum(o => o.Tidsmängd.TotalMinutes));
            }

            if (!lista.Any()) return;

            var max = lista.Max(o => o.Value);
            var xposition = 10;
            foreach (var d in lista)
            {
                var stapel = new Dagstapel
                                 {
                                     Height = panel1.Height - 20,
                                     Top = 10,
                                     Left = xposition
                                 };

                stapel.VisaUppgifter(d.Key, d.Value, max);
                xposition += stapel.Width;
                panel1.Controls.Add(stapel);
            }
        }
Example #5
0
    private string Calc(List<string> lst)
    {
        var str = "";
        foreach (var item in lst)
        {
            var dict2 = new Dictionary<int, float>();
            for (int i = 0; i < CodeArray.Length; i++)
            {
                var match = new MatchsMaker(item, CodeArray[i]);
                dict2.Add(i, match.Score);
            }

            var idx = dict2.First(p => p.Value == dict2.Max(x => x.Value)).Key;
            switch (idx)
            {
                case 10:
                    idx = 1;
                    break;
                case 11:
                case 12:
                    idx = 0;
                    break;
                default:
                    break;
            }

            str += idx;
        }
        return str;
    }
        public TimeIntervalsDlg(Dictionary<string, DateTime> intervals)
            : this()
        {
            var nowTime = DateTime.Now;
            var maxValue = Math.Max(MaxValue, intervals.Max(i => (int) Math.Round((nowTime - i.Value).TotalDays)));

            foreach (var inter in intervals)
            {
                var ctrl = new TimeIntervalControl(inter.Key, MinValue, maxValue,
                                                   (int) Math.Round((nowTime - inter.Value).TotalDays))
                               {
                                   Height = LineHeight,
                                   Dock = DockStyle.Top
                               };
                timeControls.Add(inter.Key, ctrl);
                panelContent.Controls.Add(ctrl);
            }

            if (intervals.Count > 1)
            {
                var defaultTotal = timeControls.Values.Mode(i => i.Value);
                // контрол, масштабирующий все остальные контролы
                scaleControl = new TimeIntervalControl(Localizer.GetString("TitleAll"), MinValue, maxValue, defaultTotal)
                    {
                        Height = LineHeight,
                        Dock = DockStyle.Top,
                        fontTitle = new Font(Font, FontStyle.Bold)
                    };
                scaleControl.ValueChangedByDragging += ScaleControlOnValueChangedByDragging;
                panelContent.Controls.Add(scaleControl);
            }
        }
Example #7
0
        public Response Speak()
        {
            Dictionary<Rule, int> acceptDict = new Dictionary<Rule, int>();

            foreach (Rule rule in _ruleDb)
            {
                if (!rule.CanMatch())
                    continue;

                bool match = true;
                foreach (Criterion criterion in rule.Criteria)
                {
                    if (!_factDict.ContainsKey(criterion.Lhs) || !criterion.Compare(_factDict[criterion.Lhs] as IComparable))
                    {
                        match = false;
                        break;
                    }
                }
                if (match)
                    acceptDict.Add(rule, rule.Criteria.Count);
            }
            if (acceptDict.Count == 0)
                return new Response("NullResponse", "NO RESPONSE");

            // Of all the matched rules, find the one(s) that match the most criteria
            int maxScore = acceptDict.Max(kvp => kvp.Value);
            List<Rule> acceptList = acceptDict.Where(kvp => kvp.Value == maxScore).Select(kvp => kvp.Key).ToList();

            // Of all the matched rules of maximum criteria, return a random one
            Rule matchedRule = acceptList.RandomItem();
            matchedRule.Match();
            Response response = matchedRule.Response;
            response.Match();
            return response;
        }
 public static void Main()
 {
     Dictionary<int, int> perimeters = new Dictionary<int, int>();
     for (int i = 12; i < 1001; i += 4)
     {
         for (int j = 3; j < 334; j++)
         {
             for (int k = j; k < (i - j) / 2; k++)
             {
                 if ((i - j - k) * (i - j - k) == j * j + k * k)
                 {
                     if (perimeters.ContainsKey(i))
                     {
                         perimeters[i]++;
                     }
                     else
                     {
                         perimeters.Add(i, 1);
                     }
                 }
             }
         }
     }
     var n = perimeters.Max(p => p.Value);
     var answer = perimeters.First(q => q.Value == n).Key;
     Console.WriteLine(answer);
 }
Example #9
0
        public Dictionary<int, double> CalculateDesPoints(double alpha, double beta)
        {
            Dictionary<int, double> resultDataSet = new Dictionary<int, double>();

            double sPrev = _originalDataset[2];
            double bPrev = _originalDataset[2] - _originalDataset[1];
            resultDataSet[3] = CalculateForeCast(sPrev, bPrev);

            foreach (KeyValuePair<int, double> pair in _originalDataset.Where((x, i) => i > 1))
            {
                double sNew = CalculateS1(alpha, pair.Value, sPrev, bPrev);
                double bNew = CalculateB1(alpha, beta, sNew, sPrev, bPrev);

                resultDataSet.Add(pair.Key + 1, CalculateForeCast(sNew, bNew));

                sPrev = sNew;
                bPrev = bNew;
            }

            int iterator = 2;

            for (int i = resultDataSet.Max(m=>m.Key) + 1; i < _lines; i++)
            {
                resultDataSet.Add(i, sPrev + (iterator * bPrev));
                iterator++;
            }

            return resultDataSet;
        }
Example #10
0
        protected virtual int[] GetMaxValue(Dictionary<int, Card> cards)
        {
            var max = cards.Max(x => x.Value.DenoteValue);

            var indexWithMax = cards.Where(c => c.Value.DenoteValue == max)
                .Select(c => c.Key).ToArray();

            return indexWithMax;
        }
        public int Down(string tableName, string primaryColumn, Int64 primaryValue, string orderColumn, Int64 orderNumber)
        {
            var data = new Dictionary<string, Int64>();
            using (DataCommand cmd = DataCommandManager.GetDataCommand("CommonDown"))
            {
                cmd.CommandText = string.Format(cmd.CommandText, tableName, primaryColumn, primaryValue, orderColumn,orderNumber);
                using (IDataReader dr = cmd.ExecuteDataReader())
                {
                    while (dr.Read())
                    {
                        if (!Convert.IsDBNull(dr[primaryColumn]) && !Convert.IsDBNull(dr[orderColumn]))
                        {
                            data.Add(dr[primaryColumn].ToString(), Convert.ToInt64(dr[orderColumn]));
                        }
                    }
                }

                if (data.Count == 1)
                {
                    return 2;
                }
                else
                {
                    string sql = "update {0} set {1}={2} where {3}={4}";

                    StringBuilder sb = new StringBuilder();
                    foreach (KeyValuePair<string, long> keyValuePair in data)
                    {
                        if (keyValuePair.Key == primaryValue.ToString())
                        {
                            sb.Append(
                                string.Format(
                                    sql,
                                    tableName,
                                    orderColumn,
                                    data.Min(s => s.Value),
                                    primaryColumn,
                                    primaryValue) + ";");

                        }
                        else
                        {
                            sb.Append(
                                string.Format(
                                    sql,
                                    tableName,
                                    orderColumn,
                                    data.Max(s => s.Value),
                                    primaryColumn,
                                    keyValuePair.Key) + ";");
                        }
                    }
                    cmd.CommandText = sb.ToString();
                    return cmd.ExecuteNonQuery();
                }
            }
        }
Example #12
0
        public static void SetChart(Dictionary<string, int> rawValues, Chart chart)
        {
            int fmin = 0;
            int fmax = 1;

            if (rawValues.Count > 0)
            {
                fmax = rawValues.Max(x => x.Value);
                fmin = rawValues.Min(x => x.Value);
            }

            //series init
            chart.Series.Clear();
            //   chart.Tag = values;
            var s = new Series();
            s.ChartType = SeriesChartType.Bar;

            foreach (var kvp in rawValues)
            {
                s.Points.AddXY(kvp.Key, kvp.Value);
                var dpc = s.Points[s.Points.Count - 1];
                dpc.Color = ColorExtras.GetRedGreenBlendedColour(kvp.Value, 0, fmax);
                dpc.ToolTip = kvp.Key + ":" + kvp.Value;
            }

            s.YAxisType = AxisType.Primary;
            s.XAxisType = AxisType.Secondary;
            s.IsVisibleInLegend = false;
            chart.Series.Add(s);
            //chartarea init
            chart.ChartAreas.Clear();
            var ca = new ChartArea();

              //  ca.CursorX.IsUserEnabled = true;
               // ca.CursorX.IsUserSelectionEnabled = true;

            ca.AxisX2.ScrollBar.IsPositionedInside = false;
            ca.AxisX2.ScaleView.Size = zoomMax;
            ca.AxisX2.ScaleView.Position=rawValues.Count-ca.AxisX2.ScaleView.Size;

            ca.AxisX2.Interval = 1;
            ca.AxisY.Interval = MathExtras.Ceiling((Math.Abs(fmax) - Math.Abs(fmin)) / 8);
            if (ca.AxisY.Interval<1)
                ca.AxisY.Interval = 1;

            ca.AxisY.Minimum = fmin;
            ca.AxisY.Maximum = fmax;
            if (Math.Abs(ca.AxisY.Minimum - ca.AxisY.Maximum) < 1)
                ca.AxisY.Minimum--;

            s.Sort(PointSortOrder.Ascending);
            chart.ChartAreas.Add(ca);
        }
Example #13
0
        static void Main(string[] args)
        {
            string[] input = File.ReadAllLines("input.txt");

            foreach (string line in input)
            {
                Reindeers.Add(ParseReindeer(line));
            }

            Dictionary<Reindeer, int> raceDistancesStar1 = new Dictionary<Reindeer, int>();
            raceDistancesStar1 = CalculateRace(2503);

            foreach (KeyValuePair<Reindeer, int> raceDistance in raceDistancesStar1.OrderByDescending(d => d.Value))
            {
                Console.WriteLine($"Reindeer: {raceDistance.Key.Name}, Distance: {raceDistance.Value}");
            }

            Console.WriteLine($"Day 14 - Star 1, Answer: {raceDistancesStar1.OrderByDescending(rd => rd.Value).First().Key.Name} - {raceDistancesStar1.OrderByDescending(rd => rd.Value).First().Value} km");

            Dictionary<Reindeer, int> extraPoints = new Dictionary<Reindeer, int>();

            Dictionary<Reindeer, int> raceDistancesStar2 = new Dictionary<Reindeer, int>();

            for (int i = 1; i <= 2503; i++)
            {
                raceDistancesStar2 = CalculateRace(i);

                // Give current leading reindeer(s) bonus point
                IEnumerable<KeyValuePair<Reindeer, int>> leadingReindeers = raceDistancesStar2.Where(rd => rd.Value == raceDistancesStar2.Max(d => d.Value));

                foreach (KeyValuePair<Reindeer, int> leadingReindeer in leadingReindeers)
                {
                    if (!extraPoints.ContainsKey(leadingReindeer.Key))
                    {
                        extraPoints.Add(leadingReindeer.Key, 0);
                    }

                    extraPoints[leadingReindeer.Key]++;
                }
            }

            foreach (KeyValuePair<Reindeer, int> raceDistance in raceDistancesStar2.OrderByDescending(d => d.Value))
            {
                int points = 0;
                extraPoints.TryGetValue(raceDistance.Key, out points);

                Console.WriteLine($"Reindeer: {raceDistance.Key.Name}, Distance: {raceDistance.Value}, Points: {points}");
            }

            Console.WriteLine($"Day 14 - Star 2, Answer: {extraPoints.OrderByDescending(rd => rd.Value).First().Key.Name} - {extraPoints.OrderByDescending(rd => rd.Value).First().Value} points");

            Console.ReadKey();
        }
Example #14
0
        public long Solve()
        {
            var primes = new Prime(Limit);

            var numberDivisors = new Dictionary<int, int>();
            for (var number = 1; number <= Limit; number++)
            {
                var decomposition = primes.GetDecomposition(number);

                var sum = 1;
                foreach (var divisor in decomposition)
                {
                    sum *= this.GetSumDivisors(divisor);
                }
                sum -= number;

                if (sum < Limit && sum != 1)
                {
                    numberDivisors.Add(number, sum);
                }
            }

            var lines = new Dictionary<long, long>();
            foreach (var numberDivisor in numberDivisors)
            {
                var minValueStart = numberDivisor.Key;
                var nextValue = numberDivisor.Value;
                var group = new HashSet<int> { minValueStart };
                var currentCount = 1;

                while (minValueStart != nextValue && nextValue > minValueStart && currentCount == group.Count)
                {
                    if (numberDivisors.ContainsKey(nextValue))
                    {
                        group.Add(nextValue);
                        nextValue = numberDivisors[nextValue];
                        currentCount++;
                    }
                    else
                    {
                        nextValue = 0;
                    }
                }

                if (nextValue == minValueStart && group.Count > 1)
                {
                    lines.Add(minValueStart, group.Count);
                }
            }

            return lines.Where(t => t.Value == lines.Max(r => r.Value)).Min(t => t.Key);
        }
        static void PrintBestSequence(Dictionary<string, int> occurrences)
        {
            int bestCount = occurrences.Max(key => key.Value);
            // Match the best count with the first value it finds
            var bestEntry
                = occurrences.First(key => key.Value == bestCount).Key;

            Console.WriteLine(bestCount);
            for (int i = 0; i < bestCount; i++)
            {
                Console.WriteLine(bestEntry);
            }
        }
        void EnsureCanMigrate(long toVersion, Dictionary<long, Type> migrationTypes, Assembly assemblyContainingMigrations)
        {
            if (migrationTypes.Count == 0)
            {
                throw new ArgumentException("No migrations defined in assembly " + assemblyContainingMigrations.FullName + ".");
            }

            if (toVersion > 0 && !migrationTypes.ContainsKey(toVersion))
            {
                var availableMaxVersion = migrationTypes.Max(t => t.Key);
                throw new ArgumentException("Migration not defined for version " + toVersion + ". Omit the ToVersion parameter to migrate to the maximum version. The maximum migration version available is " + availableMaxVersion + ".");
            }
        }
        public void FindPermutationsOfCubes()
        {
            const long lowerLimit = 99999999999;
            const long upperLimit = 1000000000000;

            var dict = new Dictionary<string, List<long>>();

            long n = 0;
            long cube = CubeHelper.GetCube(n);
            while (cube < upperLimit)
            {
                if (cube > lowerLimit)
                {
                    var digits = DigitHelper.GetDigits(cube);
                    var key = string.Concat(digits.OrderBy(d => d));
                    if (!dict.ContainsKey(key))
                        dict.Add(key, new List<long>());

                    dict[key].Add(cube);
                }

                n++;
                cube = CubeHelper.GetCube(n);
            }

            if (dict.Values.Any(c => c.Count == 5))
            {
                foreach (var dictEntry in dict.Where(kvp => kvp.Value.Count == 5))
                {
                    Console.WriteLine("Key: {0}", dictEntry.Key);
                    Console.WriteLine(string.Join(",", dictEntry.Value));
                }
            }
            else
            {
                Console.WriteLine("No five cube set");
                Console.WriteLine("Max entries: {0}", dict.Max(de => de.Value.Count));
            }

            if (dict.ContainsKey("01234566"))
            {
                Console.WriteLine(string.Join(",", dict["01234566"]));
            }

            // 41063625
            // 01234566
        }
Example #18
0
        static int BruteForce(int num, int maxPrime)
        {
            var map = new Dictionary<int, int>();
            var primes = GetPrimesBelow(maxPrime).ToArray();
            var count = primes.Length;
            for (int i = num; i > 100; i = i - 2)
            {
                if(MathUtils.IsPrime(i))
                {
                    if(!map.ContainsKey(i))
                    {
                        map.Add(i, 0);
                    }

                    int max = 0;
                    int j = 0;

                    while (max + j < count)
                    {
                        var temp = primes[j];
                        for (int k = j + 1; k < count; k++)
                        {
                            temp += primes[k];
                            if(temp == i)
                            {
                                var max1 = k - j + 1;
                                max = max > max1 ? max : max1;
                                break;
                            }
                            else if(temp > i)
                            {
                                break;
                            }
                        }

                        j ++;
                    }

                    map[i] = max;

                }
            }

            var times = map.Max(x => x.Value);
            return map.First(x => x.Value == times).Key;
        }
Example #19
0
    public static double CalcDiscount(ShoppingCart sCart, double totPrice)
    {
      //Calc Harry Potter series discount
      Dictionary<IList<int>, double> combinations = new Dictionary<IList<int>, double>();

      //Search for all combination between 2-5 (the one's you got discount for)
      for (int i = 5; i >= 2; i--)
      {
        double discount = 0;
        var uniqueTitles = sCart.Items.Select(x => x.Title).Distinct();
        HashSet<Guid> handled = new HashSet<Guid>(); //To know calculated
        IList<int> uniqueSets = new List<int>();

        while (sCart.Items.Any(x => !handled.Contains(x.Id)))
        {
          HashSet<string> tmpTitles = new HashSet<string>();
          var uniques = sCart.Items.Where(x => !handled.Contains(x.Id));
          foreach (var sItem in uniques)
          {
            if (tmpTitles.Count <= i && !tmpTitles.Contains(sItem.Title))
            {
              tmpTitles.Add(sItem.Title);
              handled.Add(sItem.Id);
            }
          }

          uniqueSets.Add(tmpTitles.Count);
        }

        //Calculate discount for each set
        foreach (int uni in uniqueSets)
        {
          double price = sCart.Items.First().Price;
          discount += CalcSetDiscount(uni, price);
        }

        //Save the total discount for this combination
        combinations.Add(uniqueSets, discount);
      }     

      //Pick the comination with highest possible discount
      return combinations.Max(x => x.Value);
    }
Example #20
0
        public string Classify(double[] obj)
        {
            Dictionary<string, double> score = new Dictionary<string, double>();

            var results = (from myRow in dataSet.Tables[0].AsEnumerable()
                           group myRow by myRow.Field<string>(dataSet.Tables[0].Columns[0].ColumnName) into g
                           select new { Name = g.Key, Count = g.Count() }).ToList();

            for (int i = 0; i < results.Count; i++)
            {
                List<double> subScoreList = new List<double>();
                int a = 1, b = 1;
                for (int k = 1; k < dataSet.Tables["Gaussian"].Columns.Count; k = k + 2)
                {
                    double mean = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][a]);
                    double variance = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][++a]);
                    double result = Helper.NormalDist(obj[b - 1], mean, Helper.SquareRoot(variance));
                    subScoreList.Add(result);
                    a++; b++;
                }

                double finalScore = 0;
                for (int z = 0; z < subScoreList.Count; z++)
                {
                    if (finalScore == 0)
                    {
                        finalScore = subScoreList[z];
                        continue;
                    }

                    finalScore = finalScore * subScoreList[z];
                }

                score.Add(results[i].Name, finalScore * 0.5);
            }

            double maxOne = score.Max(c => c.Value);
            var name = (from c in score
                        where c.Value == maxOne
                        select c.Key).First();

            return name;
        }
        public string GetBestMatchingTitle( string searchInput, IEnumerable<string> titles )
        {
            var titleToSimilarityMap = new Dictionary<string, float>();
            foreach ( var title in titles )
            {
                titleToSimilarityMap.Add( title, this._titleSimilarity.Similarity( searchInput, title ) );
            }

            var maxSimilarity = titleToSimilarityMap.Max( kvp => kvp.Value );
            if ( maxSimilarity > THRESHOLD )
            {
                var firstEntryWithMaxSimilairty = titleToSimilarityMap.First( kvp => kvp.Value == maxSimilarity );
                return firstEntryWithMaxSimilairty.Key;
            }
            else
            {
                throw new Exception();  // TODO: Should I throw this TYPE of exception?
            }
        }
Example #22
0
        public void Process(IList<short[]> data)
        {
            var length = data.First().Length;
            var median = new short[length];
            var rates = new Dictionary<int, int>();

            for (int i = 0; i < length; i++)
            {
                rates.Clear();
                for (var j = 0; j < data.Count; j++)
                    if (!rates.ContainsKey(data[j][i]))
                        rates.Add(data[j][i], 1);
                    else
                        ++rates[data[j][i]];
                var popularValue = rates.Max(x => x.Value);
                median[i] = Convert.ToInt16(rates.Where(x => x.Value == popularValue).Select(y => y.Key).Average());
            }

            data.Clear();
            data.Add(median);
        }
Example #23
0
        public void WriteHelp()
        {
            _output.WriteInfoLine("CSBuild", true);
            _output.WriteInfoLine("Version: " + _buildEnvironment.Version, true);
            _output.WriteInfoLine();
            var arguments = new Dictionary<string, string>
            {
                {"-help", "Shows this help message."},
                {"-target=<task>", "Specifies which task to run."},
                {"-tasklist", "Displays a list of all available tasks."},
                {"-dryrun", "Displays a list of all tasks that will be executed. Can be combined with -target=<task>."}
            };

            var maxParamNameWidth = arguments.Max(x => x.Key.Length);
            foreach (var p in arguments)
            {
                _output.WriteInfo(p.Key + new string(' ', maxParamNameWidth - p.Key.Length), true);
                _output.WriteInfo("  :  ");
                _output.WriteInfoLine(p.Value);
            }
        }
Example #24
0
    static void Main()
    {
        int[] array = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 };

        Dictionary<int, int> elementsInArray = new Dictionary<int, int>();

        for (int i = 0; i < array.Length; i++)
        {
            if (elementsInArray.ContainsKey(array[i]))
            {
                elementsInArray[array[i]] += 1;
            }
            else
            {
                elementsInArray.Add(array[i], 1);
            }
        }
        int number = elementsInArray.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;
        int count = elementsInArray.Max(x => x.Value);
        Console.WriteLine("{0} ({1} times)", number, count);
    }
        public int FindWinner(int[] inputArray)
        {
            Dictionary<int, int> winnersD = new Dictionary<int, int>();
            //winnersD.OrderBy(x => x.Key);

            int result = 0;
            foreach (var winner in inputArray)
            {
                if (winnersD.ContainsKey(winner))
                    winnersD[winner] = winnersD[winner] + 1;
                else
                    winnersD.Add(winner, 1);

                var numWins = winnersD.Max(x => x.Value);
                //var numWins = winnersD.Aggregate((l, r) => l.Value > r.Value ? l : r).Value;

                result = winnersD.First(x => x.Value == numWins).Key;
            }

            return result;

        }
Example #26
0
        public void Save(Dictionary<string, List<News>> news)
        {
            decimal min = news.Min(n => n.Value.Min(m => m.RawScore));
            decimal max = news.Max(n => n.Value.Max(m => m.RawScore));

            using (var dbContext = new DistrictsInTownModelContainer())
            {
                foreach (var district in news)
                    AddArticlesToDB(dbContext, district, min, max);

                try
                {
                    dbContext.SaveChanges();
                }
                catch (Exception error)
                {
                    Console.WriteLine(error.StackTrace);
                }

                Console.WriteLine("Total results: {0}", news.Sum(n => n.Value.Count));
            }
        }
Example #27
0
        internal void Fold(Dictionary<Int32,FoldRegion> regions)
        {
            if (regions.Count == 0)
                return;

            var start = regions.Min(rv => rv.Key);
            var end = regions.Max(rv => rv.Value.EndLine);
            var lc =  @ref.Send(Sci.SCI_GETLINECOUNT);

            for (var i = start; i < end + 2; i++)
            {
                FoldRegion reg;

                if (regions.TryGetValue(i, out reg))
                {
                    //System.Diagnostics.Debug.WriteLine("sl=" + i + ";el=" + reg.EndLine + ";level=" + reg.Level);
                    ProcessRegion(ref i, 0, regions, reg);
                    i--;
                }
                else if (i < lc)
                    @ref.Send(Sci.SCI_SETFOLDLEVEL, i, 0 | Sci.SC_FOLDLEVELBASE);
            }
        }
Example #28
0
        // a < b < c
        // a + b > c
        // a2 + b2 = c2
        // a + b + c <= 1000

        static int BruteForce()
        {
            var map = new Dictionary<int, int>();
            for (int a = 0; a < 1000 /3; a++)
            {
                for (int b = a + 1; b < 1000/2; b++)
                {
                    for (int c = b + 1; c < 1000/2; c++)
                    {
                        if(IsTriangle(a, b, c))
                        {
                            var sum = a + b + c;
                            if(!map.ContainsKey(sum))
                            {
                                map.Add(sum, 0);
                            }
                            map[sum] ++;
                        }
                    }
                }
            }
            var max = map.Max(obj => obj.Value);
            return map.First(v => v.Value == max).Key;
        }
Example #29
0
        public string Classify(double[] testedData)
        {
            var distanceList = new List<DigitData>();

              //Calculating the distance
              foreach(var trainingData in _trainingSet)
              {
            trainingData.Distance = EuclideanDistance(trainingData.Feature, testedData);

            distanceList.Add(trainingData);
              }

              //Sort based on distance
              distanceList.Sort();

              var majoritySubset = new Dictionary<string, int>();

              for(var i=0;i<K;i++)
              {
            var resultClass = distanceList[i];

            if(majoritySubset.ContainsKey(resultClass.Label))
            {
              majoritySubset[resultClass.Label] += 1;
            }else
            {
              majoritySubset.Add(resultClass.Label, 1);
            }

              }

              //Find the majority class in the K subset
              var label = majoritySubset.Max(c => c.Key);

              return label;
        }
        public Dictionary<int, int> GetParts(Dictionary<int, int> results)
        {
            Dictionary<int, int> newResults = new Dictionary<int, int>();

            int allAnswers = results.Sum(r => r.Value);
            int sumParts = 0;

            foreach (var result in results)
            {
                double part = allAnswers != 0 ? (double)result.Value / (double)allAnswers : 0;
                int percents = int.Parse(Math.Round(part * 100, 0).ToString());
                newResults.Add(result.Key, percents);
                sumParts += percents;
            }

            if (sumParts != 100 && sumParts != 0)
            {
                var correlation = 100-sumParts;
                var maxPart = newResults.FirstOrDefault(d=>d.Value.Equals(newResults.Max(t=>t.Value)));
                newResults[maxPart.Key] = maxPart.Value + correlation;
            }

            return newResults;
        }