Example #1
0
        public static string Correct(string word)
        {
            if (string.IsNullOrEmpty(word))
                return word;

            word = word.ToLower();

            if (_dictionary.ContainsKey(word))
                return word;

            List<String> list = Edits(word);
            Dictionary<string, int> candidates = new Dictionary<string, int>();

            FindCandidates(list, ref candidates);

            if (candidates.Count > 0)
                return candidates.OrderByDescending(x => x.Value).First().Key;

            foreach (string item in list)
            {
                FindCandidates(Edits(item), ref candidates);
            }

            return (candidates.Count > 0) ? candidates.OrderByDescending(x => x.Value).First().Key : word;
        }
            public string Correct(string word)
            {
                if (string.IsNullOrEmpty(word))
                    return word;

                word = word.ToLower();

                // known()
                if (_dictionary.ContainsKey(word))
                    return word;

                List<String> list = Edits(word);
                Dictionary<string, int> candidates = new Dictionary<string, int>();

                foreach (string wordVariation in list)
                {
                    if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
                        candidates.Add(wordVariation, _dictionary[wordVariation]);
                }

                if (candidates.Count > 0)
                    return candidates.OrderByDescending(x => x.Value).First().Key;

                // known_edits2()
                foreach (string item in list)
                {
                    foreach (string wordVariation in Edits(item))
                    {
                        if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
                            candidates.Add(wordVariation, _dictionary[wordVariation]);
                    }
                }

                return (candidates.Count > 0) ? candidates.OrderByDescending(x => x.Value).First().Key : word;
            }
Example #3
0
 /// <summary>
 /// Sort the collection in the proper manner.
 /// </summary>
 internal static Dictionary<string, ListDictionary> SortCollection(Dictionary<string, ListDictionary> collection, string treeLevel, string sortLevel)
 {
     switch (sortLevel)
     {
         case "Alphabet":
             return collection
                 .OrderBy(kvp => kvp.Key)
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Effort":
             return collection
                 .OrderByDescending(kvp => kvp.Value["effort"])
                 .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Priority":
             return collection
                 .OrderByDescending(kvp => kvp.Value["priority"])
                 .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Product":
             var missingTeamString = SimpleWorkItem.GetMissingString("Team");
             var missingTeamCollection = collection.Where(kvp => kvp.Key == missingTeamString); // Reference the 'NO TEAM' grouping.
             return collection
                 .Where(kvp => kvp.Key != missingTeamString) // Exclude 'NO TEAM' from sorting.
                 .OrderBy(kvp => kvp.Key != "Atlas")
                 .ThenBy(kvp => kvp.Key != "Anubis")
                 .ThenBy(kvp => kvp.Key != "Proteus")
                 .ThenBy(kvp => kvp.Key != "Shiva")
                 .ThenBy(kvp => kvp.Key != "Janus")
                 .ThenBy(kvp => kvp.Key != "Phoenix")
                 .ThenBy(kvp => kvp.Key != "Brahma")
                 .ThenBy(kvp => kvp.Key != "Loki")
                 .ThenBy(kvp => kvp.Key != "Heimdall")
                 .ThenBy(kvp => kvp.Key != "Vulcan")
                 .ThenBy(kvp => kvp.Key != "Athena")
                 .ThenBy(kvp => kvp.Key != "Ra")
                 .ThenBy(kvp => kvp.Key) // Any unmentioned teams above will be sorted alphabetically.
                 .Concat(missingTeamCollection) // Attach 'NO TEAM' back on.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Date":
             const string futureString = "Future";
             var missingString = SimpleWorkItem.GetMissingString(treeLevel);
             var futureCollection = collection.Where(kvp => kvp.Key == futureString); // Reference the Future grouping.
             var missingCollection = collection.Where(kvp => kvp.Key == missingString); // Reference the missing grouping.
             return collection
                 .Where(kvp => kvp.Key != futureString && kvp.Key != missingString) // Exclude Future and missing from sorting.
                 .OrderBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(0, "Z")) // Sort by Year, using "Z" to place it last if it's missing.
                 .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(1, "Z")) // Sort by Quarter, using "Z" to place it last if it's missing.
                 .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(2, "Z")) // Sort by Sprint, using "Z" to place it last if it's missing.
                 .Concat(futureCollection) // Attach Future back on.
                 .Concat(missingCollection) // Attach missing back on.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         default:
             throw new Exception("Sorting type: " + sortLevel + ", is not supported.");
     }
 }
 internal static void WriteStats(List<ChangeList> allChangelists)
 {
     var commentForTesterIsNull = 0;
     var commentForTesterIsEmpty = 0;
     var commentForTesterIsNc = 0;
     var commentForTesterIsNullByAuthor = new Dictionary<string, int>();
     var commentForTesterIsEmptyByAuthor = new Dictionary<string, int>();
     var commentForTesterIsNcByAuthor = new Dictionary<string, int>();
     foreach (var changelist in allChangelists)
     {
         var description = changelist.ParsedDescription;
         if (description.CommentForTestersTrimmed == null)
         {
             commentForTesterIsNull++;
             if (commentForTesterIsNullByAuthor.ContainsKey(changelist.Author))
                 commentForTesterIsNullByAuthor[changelist.Author]++;
             else
                 commentForTesterIsNullByAuthor[changelist.Author] = 1;
         }
         else if (description.CommentForTestersTrimmed == "")
         {
             commentForTesterIsEmpty++;
             if (commentForTesterIsEmptyByAuthor.ContainsKey(changelist.Author))
                 commentForTesterIsEmptyByAuthor[changelist.Author]++;
             else
                 commentForTesterIsEmptyByAuthor[changelist.Author] = 1;
         }
         else if (string.Equals(description.CommentForTestersTrimmed, "nc", StringComparison.OrdinalIgnoreCase))
         {
             commentForTesterIsNc++;
             if (commentForTesterIsNcByAuthor.ContainsKey(changelist.Author))
                 commentForTesterIsNcByAuthor[changelist.Author]++;
             else
                 commentForTesterIsNcByAuthor[changelist.Author] = 1;
         }
     }
     Console.WriteLine("Comment for tester is null: {0}, authors: {1}, top: {2}-{3}", commentForTesterIsNull, commentForTesterIsNullByAuthor.Count, commentForTesterIsNullByAuthor.OrderByDescending(a => a.Value).First().Key, commentForTesterIsNullByAuthor.OrderByDescending(a => a.Value).First().Value);
     Console.WriteLine("Comment for tester is empty: {0}, authors: {1}, top: {2}-{3}", commentForTesterIsEmpty, commentForTesterIsEmptyByAuthor.Count, commentForTesterIsEmptyByAuthor.OrderByDescending(a => a.Value).First().Key, commentForTesterIsEmptyByAuthor.OrderByDescending(a => a.Value).First().Value);
     Console.WriteLine("Comment for tester is nc: {0}, authors: {1}, top: {2}-{3}", commentForTesterIsNc, commentForTesterIsNcByAuthor.Count, commentForTesterIsNcByAuthor.OrderByDescending(a => a.Value).First().Key, commentForTesterIsNcByAuthor.OrderByDescending(a => a.Value).First().Value);
     Console.WriteLine("Comment for tester is null");
     foreach (var author in commentForTesterIsNullByAuthor.OrderByDescending(a => a.Value))
     {
         Console.WriteLine("{0}: {1}", author.Key, author.Value);
     }
     Console.WriteLine("Comment for tester is empty");
     foreach (var author in commentForTesterIsEmptyByAuthor.OrderByDescending(a => a.Value))
     {
         Console.WriteLine("{0}: {1}", author.Key, author.Value);
     }
     Console.WriteLine("Comment for tester is nc");
     foreach (var author in commentForTesterIsNcByAuthor.OrderByDescending(a => a.Value))
     {
         Console.WriteLine("{0}: {1}", author.Key, author.Value);
     }
 }
Example #5
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 #6
0
 static void Main(string[] args)
 {
     string s = "заданная,по,умолчанию,строка,на,входе,в,которой,производится,поиск,триплетов";
     Dictionary<string,int> triplet = new Dictionary<string,int>();      //список триплетов с количеством повторений каждого
     Console.Write("Введите строку: ");
     s=Console.ReadLine();
     int err = Check(ref s);   //проверка строки
     if (err == 0)       //строка соответствует условию, в строке больше одного триплета
     {
         int i = 3;
         string trip = s.Substring(0, 3).ToLower(); //выделение подстроки с приведением к строчным буквам (считаем триплеты «Три» и «три» одинаковыми)
         triplet.Add(trip, 1);  //первый триплет автоматически попадает в список
         while (i < s.Length)
         {
             if (Char.IsLetter(s[i]))  //продолжается ли слово
             {
                 trip = trip.Substring(1) + Char.ToLower(s[i]); //изменение триплета
                 if (triplet.ContainsKey(trip)) //есть ли уже такой триплет
                 {
                     triplet[trip]++; //увеличение количества вхождений для найденного триплета
                 }
                 else
                 {
                     triplet.Add(trip, 1); //добавление нового триплета
                 }
                 i++;
             }
             else
             {
                 trip = s.Substring(i, 3); // натолкнулись на запятую, создаём триплет, содержащий её и две следующие буквы. Так как из строки удалены слова из двух букв, триплет гарантировано будет
                 i += 3;
             }
         }
         Console.WriteLine(String.Concat(triplet.OrderByDescending(x => x.Value).FirstOrDefault().Key, " ", triplet.OrderByDescending(x => x.Value).FirstOrDefault().Value.ToString())); //выводим наиболее частый триплет и число его вхождений
     }
     else if (err == 1)  //в строке только три символа или только одно слово из трёх символов
     {
         Console.WriteLine(String.Concat(s, " 1"));
     }
     else if (err == 2) //в строке нет триплетов
     {
         Console.WriteLine("В строке нет ни одного триплета");
     }
     else //в строке присутствуют отличные от букв и запятой символы
     {
         Console.WriteLine("Строка не соответствует условию задачи");
     }
     Console.ReadKey();
 }
Example #7
0
 /// <summary>
 /// Populate asynchronously.
 /// </summary>
 /// <param name="done">The callback.</param>
 public void Populate(Action<ISeries> done) {
     _series.Populate(() => {
         _children = _series.Children.Select(x => new Chapter(x) as IChapter).ToArray();
         foreach (var source in _children.OfType<Chapter>()) {
             if (source.Number != -1) continue;
             var differential = new Dictionary<double, int>();
             var origin = null as Chapter;
             foreach (var candidate in _children.OfType<Chapter>()) {
                 if (candidate != source && candidate.Number != -1 && candidate.Volume == source.Volume) {
                     if (origin != null) {
                         var difference = Math.Round(candidate.Number - origin.Number, 4);
                         if (differential.ContainsKey(difference)) {
                             differential[difference]++;
                         } else {
                             differential[difference] = 1;
                         }
                     }
                     origin = candidate;
                 }
             }
             if (differential.Count == 0) {
                 source.Number = origin == null ? 0.5 : origin.Number + origin.Number / 2;
             } else {
                 var shift = differential.OrderByDescending(x => x.Value).FirstOrDefault().Key;
                 source.Number = Math.Round(origin.Number + (shift <= 0 || shift >= 1 ? 1 : shift) / 2, 4);
             }
         }
         done(this);
     });
 }
        static void Main(string[] args)
        {
            try
            {
                string fileSourcePath = "text.txt";
                string fileResultPath = "result.txt";
                string fileDictionaryPath = "words.txt";
                Dictionary<string, int> dictionary = new Dictionary<string, int>();

                using (StreamReader reader = new StreamReader(fileDictionaryPath, Encoding.GetEncoding("windows-1251")))
                {
                    while (!reader.EndOfStream)
                    {
                        string word = reader.ReadLine();
                        dictionary.Add(word, 0);
                    }
                }
                using (StreamReader reader = new StreamReader(fileSourcePath, Encoding.GetEncoding("windows-1251")))
                {
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();

                        List<string> wordList = new List<string>(dictionary.Keys);

                        foreach (string word in wordList)
                        {
                            string regex = String.Format("\\b{0}\\b", word);
                            MatchCollection matches = Regex.Matches(line, regex);
                            dictionary[word] += matches.Count;
                        }
                    }
                }
                using (StreamWriter writer = new StreamWriter(fileResultPath, false, Encoding.GetEncoding("windows-1251")))
                {
                    foreach (var wordCounter in dictionary.OrderByDescending(key => key.Value))
                    {
                        writer.Write(wordCounter.Key);
                        writer.Write("-");
                        writer.WriteLine(wordCounter.Value);
                    }
                }
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("Path is null");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("File not found");
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine("Directory not found");
            }
            catch (IOException)
            {
                Console.WriteLine("IO exception");
            }
        }
        /// <summary>
        /// Given an input feature, a feature space and its associated labels, and a positive integer 'k',
        /// Determines the 'k' nearest neighbor label for the input feature. The 'k' value corresponds
        /// to the number of nearest neighbors to use in the voting process.
        /// 
        /// <remarks> 
        /// "When I have this grid of data points, and I provide one additional example row, find the 'k' number
        /// of rows that are most similar, count up the number of occurrences of each label for each row (1 to 'k'), 
        /// and choose the label with the highest occurrence."
        /// </remarks> 
        /// <see href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm" />
        /// </summary>
        /// <param name="distanceType">The type of equation to use when measuring the distance between each data point</param>
        /// <param name="input">The matrix row to input; must have the same number of columns as the feature space</param>
        /// <param name="featureSpace">The feature space matrix; everything we know</param>
        /// <param name="labels">The results for each feature space row; what we call each collection of data points</param>
        /// <param name="k">The number of nearest neighbors to include in the voting; the label with the most occurrences in 'k' neighbors wins</param>
        /// <returns></returns>
        public static string Classify(DistanceType distanceType, Number[] input, Matrix featureSpace, IList<string> labels, int k)
        {
            if (labels.Count() != featureSpace.Rows)
            {
                throw new ArgumentException("The number of labels must match the number of rows of data in the feature space", "labels");
            }

            var distances = CalculateDistances(distanceType, featureSpace, input);

            var nearestNeighbors = distances.OrderByDescending(d => d.Value).Take(k);

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

            foreach (var label in nearestNeighbors.Select(neighbor => labels[neighbor.Key]))
            {
                if (votes.ContainsKey(label))
                {
                    votes[label]++;
                }
                else
                {
                    votes.Add(label, 1);
                }
            }

            var nearest = votes.OrderByDescending(v => v.Value).First().Key;

            return nearest;
        }
 static void Main()
 {
     Dictionary<string, Dictionary<string, int>> stats = new Dictionary<string, Dictionary<string, int>>();
     string input;
     string pattern1 = @"^([A-Za-z]+\s*[A-Za-z]*)\s*\|\s*([A-Za-z]+[\s.'A-Za-z0-9-]*)";
     while ((input = Console.ReadLine()) != "report")
     {
         Match playerData = Regex.Match(input, pattern1);
         string name = playerData.Groups[1].Value.Trim();
         string country = playerData.Groups[2].Value.Trim();
         name = Regex.Replace(name, @"\s+", " ");
         country = Regex.Replace(country, @"\s+", " ");
         if(!stats.ContainsKey(country))
             stats.Add(country, new Dictionary<string, int>());
         if (!stats[country].ContainsKey(name))
             stats[country].Add(name, 1);
         else stats[country][name]++;
     }
     var sortedOutput = stats.OrderByDescending(x => x.Value.Skip(0).Sum(y => y.Value));
     foreach (var country in sortedOutput)
     {
         Console.WriteLine("{0} ({1} participants): {2} wins",
                             country.Key, country.Value.Count, country.Value.Skip(0).Sum(x => x.Value));
     }
 }
Example #11
0
        static void Main(string[] args)
        {
            const string SplitPattern = @"\s*\|\s*";
            Regex regex = new Regex(SplitPattern);

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

            string input = Console.ReadLine();

            while (input != "report")
            {
                string[] tokens = regex.Split(input.Trim());
                string athlete = Regex.Replace(tokens[0].Trim(), @"\s+", " ");
                string country = Regex.Replace(tokens[1].Trim(), @"\s+", " ");

                if (!countryData.ContainsKey(country))
                {
                    countryData.Add(country, new List<string>());
                }
                countryData[country].Add(athlete);
                input = Console.ReadLine();
            }
            var orderedCountryData = countryData
                .OrderByDescending(x => x.Value.Count);

            foreach (var country in orderedCountryData)
            {
                Console.WriteLine(
                    "{0} ({1} participants): {2} wins",
                    country.Key,
                    country.Value.Distinct().Count(),
                    country.Value.Count);
            }
        }
Example #12
0
        static void Main()
        {
            string text = @"Write a program that reads a string from the console and prints all different letters in the string along with information how many times each letter is found.";
            Dictionary<string, int> words = new Dictionary<string, int>();

            string[] wordsInText = text.Split(new char[] { '.', ',', ' ', '!', '?', '-', ':', ';' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in wordsInText)
            {
                if (words.ContainsKey(word))
                {
                    words[word]++;
                }
                else
                {
                    words.Add(word, 1);
                }
            }

            var sortedWords = words.OrderByDescending(w => w.Value);

            foreach (var word in sortedWords)
            {
                Console.WriteLine("Word \"{0}\" is found {1} time(s)", word.Key, words[word.Key]);
            }
        }
        public static int FindMajorant(List<int> input)
        {
            int majorantMargin = input.Count / 2 + 1;
            Dictionary<int, int> valueCount = new Dictionary<int, int>();

            for (int i = 0; i < input.Count; i++)
            {
                if (!valueCount.ContainsKey(input[i]))
                {
                    valueCount[input[i]] = 1;
                }
                else
                {
                    valueCount[input[i]]++;
                }

                if (valueCount[input[i]] > majorantMargin)
                {
                    return input[i];
                }
            }

            //handle case when there is no clear winner
            int majorant = valueCount.OrderByDescending(x => x.Value).Select(x => x.Key).First();

            return majorant;
        }
Example #14
0
        static void Main()
        {
            Console.WriteLine("Enter some text with repeated words: ");
            string text = Console.ReadLine();
            string regex = @"\b\w+\b";

            Dictionary<string, int> dictionary = new Dictionary<string, int>();
            MatchCollection words = Regex.Matches(text, regex);

            foreach (Match word in words)
            {
                if (dictionary.ContainsKey(word.ToString()))
                {
                    dictionary[word.ToString()] += 1;
                }
                else
                {
                    dictionary.Add(word.ToString(), 1);
                }
            }

            foreach (var word in dictionary.OrderByDescending(m => m.Value))
            {
                Console.WriteLine("{0} - {1}", word.Key, word.Value);
            }

        }
    static void Main()
    {
        StreamReader wordsReader = new StreamReader("../../words.txt");
        StreamReader textReader = new StreamReader("../../text.txt");
        StreamWriter resultWriter = new StreamWriter("../../result.txt");

        using (wordsReader)
        {
            using (textReader)
            {
                using (resultWriter)
                {
                    List<string> words = new List<string>();
                    string line = wordsReader.ReadLine();
                    while (line != null)
                    {
                        words.Add(line);
                        line = wordsReader.ReadLine();
                    }

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

                    List<string> text = new List<string>();
                    line = textReader.ReadLine();
                    while (line != null)
                    {
                        text.Add(line);
                        line = textReader.ReadLine();
                    }

                    for (int i = 0; i < words.Count; i++)
                    {
                        wordsCount.Add(0);
                        for (int j = 0; j < text.Count; j++)
                        {
                            if (text[j].ToLower().Contains(words[i].ToLower()))
                            {
                                wordsCount[i]++;
                            }
                        }
                    }

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

                    for (int i = 0; i < words.Count; i++)
                    {
                        dict[words[i]] = wordsCount[i];
                    }

                    var ordered = dict.OrderByDescending(x => x.Value);

                    foreach (var item in ordered)
                    {
                        resultWriter.WriteLine("{0} - {1}", item.Key, item.Value);
                    }

                }
            }
        }
    }
Example #16
0
    static void Main()
    {
        string[] words = File.ReadAllLines("../../words.txt");
        Dictionary<string, int> dictionary = new Dictionary<string, int>();

        using (StreamReader reader = new StreamReader("../../fileForScaning.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                for (int i = 0; i < words.Length; i++)
                {
                    string regex = @"\b" + words[i] + @"\b";
                    MatchCollection matches = Regex.Matches(line, regex,RegexOptions.IgnoreCase);
                    if (dictionary.ContainsKey(words[i]))
                    {
                        dictionary[words[i]] += matches.Count;
                    }
                    else
                    {
                        dictionary.Add(words[i], matches.Count);
                    }
                }
            }
        }

        using (StreamWriter writer = new StreamWriter("../../result.txt"))
        {
            foreach (var wordCount in dictionary.OrderByDescending(key => key.Value))
            {
                writer.WriteLine("{0} - {1}", wordCount.Key, wordCount.Value);
            }
            Console.WriteLine("Count Complete - Please Check result.txt file!");
        }
    }
Example #17
0
        private static List<StockMarket.Company> GetCurrentQuotes()
        {
            Dictionary<string, DateTime> files = new Dictionary<string, DateTime>();

            string dir = ConfigurationManager.AppSettings["QuoteDirectory"];
            if (!string.IsNullOrEmpty(dir))
            {
                foreach (System.IO.FileInfo fi in new System.IO.DirectoryInfo(dir).GetFiles("AllQuotes_*"))
                {
                    string[] nameParts = fi.FullName.Split('_');

                    if (nameParts != null && nameParts.Length > 1)
                    {
                        DateTime d = DateTime.Parse(nameParts[1]);
                        if (d != null)
                        {
                            files.Add(fi.FullName, d);
                        }
                    }

                }
                string filename = files.OrderByDescending(f => f.Value).Select(f => f.Key).FirstOrDefault();

                return filename.DeSerialze_Binary <List<StockMarket.Company>>().ToList();
            }
            return new List<StockMarket.Company>();
        }
    static void Main()
    {
        string line = Console.ReadLine();
        Dictionary<string, Dictionary<string, long>> countryData = new Dictionary<string, Dictionary<string, long>>();

        while (line != "report")
        {
            string[] lineArgs = line.Split('|');
            string city = lineArgs[0];
            string country = lineArgs[1];
            long population = long.Parse(lineArgs[2]);

            if (!countryData.ContainsKey(country))
            {
                countryData.Add(country, new Dictionary<string, long>());
            }

            countryData[country][city] = population;

            line = Console.ReadLine();
        }

        var sorted = countryData.OrderByDescending(c => c.Value.Sum(s => s.Value));

        foreach (var pair in sorted)
        {
            Console.WriteLine("{0} (total population: {1})", pair.Key, pair.Value.Sum(s => s.Value));
            foreach (var innerPair in pair.Value.OrderByDescending(c => c.Value))
            {
                Console.WriteLine("=>{0}: {1}", innerPair.Key, innerPair.Value);
            }
        }
    }
Example #19
0
 static void Main()
 {
     StreamReader wordsReader = new StreamReader("../../words.txt");
     StreamReader textReader = new StreamReader("../../text.txt");
     StreamWriter resultWriter = new StreamWriter("../../result.txt");
     List<string> wordsToMacth = FillWordsInList(wordsReader);
     var resultList = new Dictionary<string, int>();
     using (textReader)
     {
         string text = textReader.ReadToEnd();
         for (int i = 0; i < wordsToMacth.Count; i++)
         {
             string patternToMatch = string.Format(@"\b{0}\b", wordsToMacth[i]);
             Regex findWords = new Regex(patternToMatch);
             MatchCollection matchedWords = findWords.Matches(text);
             resultList.Add(wordsToMacth[i], matchedWords.Count);                           
         }
     }
     using (resultWriter)
     {
         foreach (var result in resultList
             .OrderByDescending(result=> result.Value))
         {
             Console.WriteLine("{0} - {1}", result.Key, result.Value);
         }          
     }    
 }
        /// <summary>
        /// The uninstall database schema.
        /// </summary>
        /// <param name="database">
        /// The database.
        /// </param>
        /// <param name="orderedTables">
        /// The ordered tables.
        /// </param>
        /// <param name="version">
        /// The version.
        /// </param>
        internal static void UninstallDatabaseSchema(Database database, Dictionary<int, Type> orderedTables, string version)
        {
            LogHelper.Info<DatabaseSchemaHelper>(string.Format("Start UninstallDataSchema {0}", version));

            foreach (var item in orderedTables.OrderByDescending(x => x.Key))
            {
                var tableNameAttribute = item.Value.FirstAttribute<TableNameAttribute>();

                string tableName = tableNameAttribute == null ? item.Value.Name : tableNameAttribute.Value;

                LogHelper.Info<DatabaseSchemaHelper>("Uninstall" + tableName);

                try
                {
                    if (database.TableExist(tableName))
                    {
                        database.DropTable(tableName);
                    }
                }
                catch (Exception ex)
                {
                    //swallow this for now, not sure how best to handle this with diff databases... though this is internal
                    // and only used for unit tests. If this fails its because the table doesn't exist... generally!
                    LogHelper.Error<DatabaseSchemaHelper>("Could not drop table " + tableName, ex);
                }
            }
        }
        /// <summary>
        /// Converts the hashed (MD5) Battlefield Heroes Beta file to the common text format.
        /// </summary>
        private static void ProcessBattlefieldHeroesFile()
        {
            Dictionary<string, PasswordInfo> passwords = new Dictionary<string, PasswordInfo>();
            using (TextReader reader = new StreamReader(@"../../../passwords/battlefield_heroes.csv"))
            {
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line == "")
                        continue;

                    var tokens = line.Split(';');
                    string pw = tokens.Last().Trim('"');
                    PasswordInfo val;
                    if (!passwords.TryGetValue(pw, out val))
                        passwords.Add(pw, new PasswordInfo(0,0));

                    passwords[pw].Accounts++;
                    passwords[pw].Reward++;
                }
            }
            using (TextWriter writer = new StreamWriter(@"../../../passwords/battlefield_heroes.txt"))
                foreach (var kv in passwords.OrderByDescending(s => s.Value))
                    writer.WriteLine(kv.Value + " " + kv.Key);
        }
Example #22
0
 private static void CountMatchesWords()
 {
     try
     {
         List<string> sb1 = ReadFromFile("Test1.txt");
         List<string> wordList = ReadFromFile("WordList.txt");
         var content = string.Join(Environment.NewLine, sb1);
         var match = @"\b(" + string.Join("|", wordList) + ")\\b";
         var result = Regex.Matches(content, match, RegexOptions.IgnoreCase | RegexOptions.Multiline);
         Dictionary<string, int> matches = new Dictionary<string, int>();
         foreach (var item in result)
         {
             if (matches.ContainsKey(item.ToString()))
                 matches[item.ToString()] += 1;
             else
                 matches.Add(item.ToString(), 1);
         }
         matches = matches.OrderByDescending(o => o.Value).ToDictionary(k => k.Key, v => v.Value);
         using (StreamWriter sw = new StreamWriter("result.txt"))
         {
             foreach (var key in matches.Keys)
                 sw.WriteLine(key);
         }
     }
     catch (Exception ex)
     {
     }
 }
        private static void PrintResult(Dictionary<string, int> materials, SortedDictionary<string, int> junks, string material)
        {
            string name = string.Empty;
            switch (material)
            {
                case "shards":
                    name = "Shadowmourne";
                    break;
                case "motes":
                    name = "Dragonwrath";
                    break;
                case "fragments":
                    name = "Valanyr";
                    break;
            }

            Console.WriteLine($"{name} obtained!");

            var orderedMaterials = materials.OrderByDescending(m => m.Value).ThenBy(m => m.Key);
            foreach (var m in orderedMaterials)
            {
                Console.WriteLine($"{m.Key}: {m.Value}");
            }

            foreach (var junk in junks)
            {
                Console.WriteLine($"{junk.Key}: {junk.Value}");
            }
        }
        /// <summary>
        /// Matches song titles, only matches if the titles are exactly the same, needs extending
        /// </summary>
        /// <returns></returns>
        public void MatchTheSelectedSongToTheAvailableSongs()
        {
            if (SongDetails == null)
                return;

            if (string.IsNullOrEmpty(SongDetails.TrackTitle))
                return;

            if (AvailableZuneTracks.Count() == 0)
                return;

            //this matches album songs to zune website songs in the details view
            //Hold Your Colour ---- hold your colour (Album) = MATCH
            //Hold your colour ---- hold your face = NO MATCH
            this.SelectedSong = AvailableZuneTracks.Where(song => song.TrackTitle.ToLower()
                    .Contains(SongDetails.TrackTitle.ToLower()))
                    .FirstOrDefault();

            //fallback to word matching if we can't match the title exactly
            var results = new Dictionary<TrackWithTrackNum, int>();
            foreach (var song in AvailableZuneTracks)
            {
                int weightedMatches = MatchWordsWeightedByPosition(song.TrackTitle.ToLower(), SongDetails.TrackTitle.ToLower());
                results.Add(song, weightedMatches);
            }

            //select the song with the most words matching
            var mostMatches = results.OrderByDescending(val => val.Value);
            if (mostMatches.First().Value != 0)
            {
                this.SelectedSong = mostMatches.First().Key;
            }
        }
        public override IEnumerable<IEffectChoice> GetChoices()
        {
            var subtypes = new Dictionary<string, int>();

              var cards = Controller.Opponent.Library.Concat(Controller.Opponent.Battlefield).Where(x => x.Is().Creature);

              foreach (var card in cards)
              {
            foreach (var subType in card.Subtypes)
            {
              if (!subtypes.ContainsKey(subType))
            subtypes.Add(subType, 1);
              else
              {
            subtypes[subType]++;
              }
            }
              }

              if (subtypes.Count == 0)
              {
            subtypes["elf"] = 1;
              }

              _mostCommonType = subtypes.OrderByDescending(x => x.Value).First().Key;
              yield return new DiscreteEffectChoice(subtypes.Keys.ToArray());
        }
Example #26
0
        static void Main(string[] args)
        {
            int[] array = ArrayHelpers<int>.Build(20, -10, 5);
            Console.WriteLine("Original array");
            ArrayHelpers<int>.Print(array);

            // sort the array
            ArrayHelpers<int>.Quicksort(array, 0, array.Length - 1, true);

            Console.WriteLine("Sorted array");
            ArrayHelpers<int>.Print(array);

            Dictionary<int, int> counters = new Dictionary<int, int>();
            // go through every element and increment the counter in the dictionary for that element
            for (int i = 0; i < array.Length; i++) {
                if (counters.ContainsKey(array[i])) {
                    counters[array[i]] += 1;
                } else {
                    counters[array[i]] = 1;
                }
            }

            // sort the dictionary by occurence
            counters = counters.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            Console.WriteLine("Element with the highest occurence is " + counters.First().Key);
        }
Example #27
0
        public override Dictionary<string, string> GetPlaybackOptions(string url)
        {
            Dictionary<string, string> playbackOptions = new Dictionary<string, string>();
            CookieContainer cc = new CookieContainer();
            string data = GetWebData(url, cookies: cc, cache: false);
            Regex rgx = new Regex(@"""metadataUrl"":""(?<url>[^""]*)");
            Match m = rgx.Match(data);
            if (m.Success)
            {
                JObject json = GetWebData<JObject>(m.Groups["url"].Value, cookies: cc, cache: false);
                JToken videos = json["videos"];
                if (videos != null)
                {
                    foreach(JToken video in videos)
                    {
                        string key = video["key"].Value<string>();
                        string videoUrl = video["url"].Value<string>();
                        MPUrlSourceFilter.HttpUrl httpUrl = new MPUrlSourceFilter.HttpUrl(videoUrl);
                        CookieCollection cookies = cc.GetCookies(new Uri("http://my.mail.ru"));
                        httpUrl.Cookies.Add(cookies);
                        playbackOptions.Add(key, httpUrl.ToString());
                    }
                }
            }
            playbackOptions = playbackOptions.OrderByDescending((p) =>
            {
                string resKey = p.Key.Replace("p","");
                int parsedRes = 0;
                int.TryParse(resKey, out parsedRes);
                return parsedRes;
            }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            return playbackOptions;
        }
        public static Bitmap PopularityQuantization(Bitmap bmp, int colorsNr)
        {
            Dictionary<Color, int> colorDictionary = new Dictionary<Color, int>();
            Color color;
            Bitmap result = new Bitmap(bmp.Width, bmp.Height);

            for(int i = 0; i < bmp.Width; ++i)
                for (int j = 0; j < bmp.Height; ++j)
                {
                    color = bmp.GetPixel(i, j);

                    if (!colorDictionary.ContainsKey(color))
                        colorDictionary.Add(color, 0);

                    ++colorDictionary[color];
                }

            KeyValuePair<Color, int>[] sortedColorsByFrequency = colorDictionary.OrderByDescending(f => f.Value).Take(colorsNr).ToArray();
            Color[] availableColors = new Color[colorsNr];
            int k = -1;

            foreach(var pair in sortedColorsByFrequency)
                availableColors[++k] = pair.Key;

            for (int i = 0; i < bmp.Width; ++i)
                for (int j = 0; j < bmp.Height; ++j)
                {
                    color = FindClosestColor(availableColors, bmp.GetPixel(i, j));
                    result.SetPixel(i, j, color);
                }

            return result;
        }
    static void Main(string[] args)
    {
        Datavase = new Dictionary<string, Country>();

        while (true)
        {
            string inRaw = Console.ReadLine();
            if (inRaw == "report") break;

            string[] input = inRaw.Split('|');
            string country = input[1];
            string city = input[0];
            int population = int.Parse(input[2]);

            if (Datavase.ContainsKey(country))
            {
                Datavase[country].Cities.Add(city,population);
                Datavase[country].TotalPopulation += population;
            }
            else
            {
                Datavase.Add(country,new Country());
                Datavase[country].Cities.Add(city,population);
                Datavase[country].TotalPopulation += population;
            }
        }

        var sortedCountries = Datavase.OrderByDescending(x => x.Value.TotalPopulation);

        foreach (var country in sortedCountries)
        {
            Console.WriteLine("{0} (total population: {1})",country.Key,country.Value.TotalPopulation);
            country.Value.Print();
        }
    }
Example #30
0
    private static void Main()
    {
        const string sentence = "This is some sentence.";

        var wordCounts = new Dictionary<char, int>();
        foreach (char c in sentence)
        {
            if (!char.IsLetter(c))
            {
                continue;
            }

            if (!wordCounts.ContainsKey(c))
            {
                wordCounts.Add(c, 1);
            }
            else
            {
                wordCounts[c]++;
            }
        }

        IOrderedEnumerable<KeyValuePair<char, int>> orderedWordCounts = wordCounts.OrderByDescending(x => x.Value);
        foreach (var word in orderedWordCounts)
        {
            string timesString = word.Value > 0 ? "times" : "time";
            Console.WriteLine("{0}: {1} {2}", word.Key, word.Value, timesString);
        }
    }