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;
            }
Beispiel #2
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;
        }
Beispiel #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);
     }
 }
        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();
        }
Beispiel #6
0
        // POST api/values
        public async Task <IHttpActionResult> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            var url      = "";
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            Dictionary <string, float> emo    = null;
            Dictionary <string, float> labels = null;

            foreach (var file in provider.Contents)
            {
                var filename = Guid.NewGuid().ToString() + ".png";
                var stream   = await file.ReadAsStreamAsync();

                var mem = new MemoryStream(await file.ReadAsByteArrayAsync());
                emo = getemotion(mem);


                string memetext;
                if (emo.Any())
                {
                    memetext = GetMemeText(emo);
                }
                else
                {
                    labels = GetLabels(mem);
                    if (labels.Any())
                    {
                        memetext = GetMemeTextByLabel(labels);
                    }
                    else
                    {
                        return(NotFound());
                    }
                }

                var newstream = GenerateImage(stream, memetext);
                url = saveToSThree(newstream, filename);
            }
            var q = emo?.OrderByDescending(x => x.Value).FirstOrDefault().Key ?? "";
            var o = labels?.OrderByDescending(x => x.Value).FirstOrDefault().Key ?? "";

            return(Ok(new
            {
                URL = url,
                Emotion = emo?.OrderByDescending(x => x.Value).FirstOrDefault().Key ?? "",
                Tag = labels?.OrderByDescending(x => x.Value).FirstOrDefault().Key ?? ""
            }));
        }
Beispiel #7
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();
 }
    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();
        }
    }
        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]);
            }
        }
Beispiel #10
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;
        }
        /// <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;
            }
        }
Beispiel #12
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)
     {
     }
 }
Beispiel #13
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);
        }
Beispiel #14
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()
    {
        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);
                    }

                }
            }
        }
    }
        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}");
            }
        }
Beispiel #17
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);
            }

        }
Beispiel #18
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);
            }
        }
        /// <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);
        }
Beispiel #20
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);
                }
            }
        }
Beispiel #22
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);
            }
        }
    }
Beispiel #24
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!");
        }
    }
        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;
        }
        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());
        }
Beispiel #27
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);
        }
    }
        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;
        }
 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));
     }
 }
        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;
        }
Beispiel #32
0
        private static Dictionary <string, int> GetWordRankList(List <string> words,
                                                                ref Dictionary <string, int> globalRankList)
        {
            var dict = new Dictionary <string, int>();
            int i;

            foreach (var w in words)
            {
                if (globalRankList != null)
                {
                    globalRankList.TryGetValue(w, out i);
                    globalRankList[w] = i + 1;
                }

                dict.TryGetValue(w, out i);
                dict[w] = i + 1;
            }

            globalRankList = globalRankList?.OrderByDescending(s => s.Value).ToDictionary(s => s.Key, s => s.Value);
            return(dict.OrderByDescending(s => s.Value).ToDictionary(s => s.Key, s => s.Value));
        }
Beispiel #33
0
        /// <summary>
        /// Inspect the array and return the most repeated
        /// </summary>
        /// <param name="pizzaChoice">The array to inspect</param>
        /// <param name="count">count to return</param>
        /// <returns>The most repeated Purchased objects</returns>
        public static List <string> GetMostPopular(PizzaChoice[] pizzaChoice, int count)
        {
            //creat a dictionary container
            Dictionary <PizzaChoice, int> purchCount = new Dictionary <PizzaChoice, int>();

            foreach (PizzaChoice purch in pizzaChoice)
            {
                // add the count of each topping combination
                if (!purchCount.ContainsKey(purch))
                {
                    purchCount.Add(purch, 1);
                }
                else
                {
                    purchCount[purch]++;
                }
            }

            // compile the results
            return(purchCount?.OrderByDescending(pc => pc.Value).Select(v => $"Toppings:{v.Key} ordered {v.Value} number of times").Take(count).ToList());
        }
Beispiel #34
0
        public string GetRandom(int seed = 0)
        {
            var temp           = csv?.OrderByDescending(x => x.Key).ToList();
            var adjustedGroups = new List <KeyValuePair <string, DateTime?> >();
            var counter        = 0;

            foreach (var item in temp)
            {
                counter++;
                for (var i = 0; i < counter; i++)
                {
                    adjustedGroups.Add(item);
                }
            }
            var rand   = new Random(seed);
            var num    = rand.Next(0, adjustedGroups.Count - 1);
            var winner = adjustedGroups[num];

            if (string.IsNullOrWhiteSpace(winner.Key))
            {
                throw new Exception();
            }
            return(winner.Key);
        }
Beispiel #35
0
        // This decompiler is a test bed for our library,
        // don't expect to see any quality code in here
        public static void Main(string[] args)
        {
            Options = new Options();
            CommandLine.Parser.Default.ParseArgumentsStrict(args, Options);

            Options.InputFile = Path.GetFullPath(Options.InputFile);

            if (Options.OutputFile != null)
            {
                Options.OutputFile = Path.GetFullPath(Options.OutputFile);
                Options.OutputFile = FixPathSlahes(Options.OutputFile);
            }

            var paths = new List <string>();

            if (Directory.Exists(Options.InputFile))
            {
                if (Options.OutputFile != null && File.Exists(Options.OutputFile))
                {
                    Console.Error.WriteLine("Output path is an existing file, but input is a folder.");

                    return;
                }

                paths.AddRange(Directory.GetFiles(Options.InputFile, "*.*_c", Options.RecursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
            }
            else if (File.Exists(Options.InputFile))
            {
                Options.RecursiveSearch = false;

                paths.Add(Options.InputFile);
            }

            if (paths.Count == 0)
            {
                Console.Error.WriteLine("No such file \"{0}\" or directory is empty. Did you mean to include --recursive parameter?", Options.InputFile);

                return;
            }

            CurrentFile = 0;
            TotalFiles  = paths.Count;

            if (Options.MaxParallelismThreads > 1)
            {
                Console.WriteLine("Will use {0} threads concurrently.", Options.MaxParallelismThreads);

                Parallel.ForEach(paths, new ParallelOptions {
                    MaxDegreeOfParallelism = Options.MaxParallelismThreads
                }, (path, state) =>
                {
                    ProcessFile(path);
                });
            }
            else
            {
                foreach (var path in paths)
                {
                    ProcessFile(path);
                }
            }

            if (Options.CollectStats)
            {
                Console.WriteLine();
                Console.WriteLine("Processed resource stats:");

                foreach (var stat in stats.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key))
                {
                    Console.WriteLine("{0,5} resources of version {2} and type {1}{3}", stat.Value.Count, stat.Value.Type, stat.Value.Version,
                                      stat.Value.Info != "" ? string.Format(" ({0})", stat.Value.Info) : ""
                                      );
                }

                Console.WriteLine();
                Console.WriteLine("Unique special dependancies:");

                foreach (var stat in uniqueSpecialDependancies)
                {
                    Console.WriteLine("{0} in {1}", stat.Key, stat.Value);
                }
            }
        }
        static void Main(string[] args)
        {
            var participants = new Dictionary <string, int>();
            var submissions  = new Dictionary <string, int>();

            var line = Console.ReadLine()
                       .Split("-", StringSplitOptions.RemoveEmptyEntries);

            while (line[0] != "exam finished")
            {
                var name = line[0];

                if (line[1] == "banned")
                {
                    participants.Remove(name);
                }
                else
                {
                    var language = line[1];
                    var points   = int.Parse(line[2]);

                    if (participants.ContainsKey(name) == false)
                    {
                        participants[name] = points;

                        if (submissions.ContainsKey(language) == false)
                        {
                            submissions[language] = 1;
                        }
                        else
                        {
                            submissions[language]++;
                        }
                    }
                    else
                    {
                        if (participants[name] < points)
                        {
                            participants[name] = points;

                            submissions[language]++;
                        }
                        else
                        {
                            if (submissions.ContainsKey(language) == false)
                            {
                                submissions[language] = 1;
                            }
                            else
                            {
                                submissions[language]++;
                            }
                        }
                    }
                }

                line = Console.ReadLine()
                       .Split("-", StringSplitOptions.RemoveEmptyEntries);
            }

            Console.WriteLine("Results:");

            foreach (var name in participants.OrderByDescending(n => n.Value).ThenBy(v => v.Key))
            {
                Console.WriteLine($"{name.Key} | {name.Value}");
            }

            Console.WriteLine("Submissions:");

            foreach (var sub in submissions.OrderByDescending(s => s.Value).ThenBy(l => l.Key))
            {
                Console.WriteLine($"{sub.Key} - {sub.Value}");
            }
        }
Beispiel #37
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected virtual void PopulateMigrations(
            IEnumerable <string> appliedMigrationEntries,
            string targetMigration,
            out IReadOnlyList <Migration> migrationsToApply,
            out IReadOnlyList <Migration> migrationsToRevert,
            out Migration actualTargetMigration)
        {
            var appliedMigrations        = new Dictionary <string, TypeInfo>();
            var unappliedMigrations      = new Dictionary <string, TypeInfo>();
            var appliedMigrationEntrySet = new HashSet <string>(appliedMigrationEntries, StringComparer.OrdinalIgnoreCase);

            if (_migrationsAssembly.Migrations.Count == 0)
            {
                _logger.MigrationsNotFound(this, _migrationsAssembly);
            }

            foreach (var migration in _migrationsAssembly.Migrations)
            {
                if (appliedMigrationEntrySet.Contains(migration.Key))
                {
                    appliedMigrations.Add(migration.Key, migration.Value);
                }
                else
                {
                    unappliedMigrations.Add(migration.Key, migration.Value);
                }
            }

            if (string.IsNullOrEmpty(targetMigration))
            {
                migrationsToApply = unappliedMigrations
                                    .OrderBy(m => m.Key)
                                    .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider))
                                    .ToList();
                migrationsToRevert    = Array.Empty <Migration>();
                actualTargetMigration = null;
            }
            else if (targetMigration == Migration.InitialDatabase)
            {
                migrationsToApply  = Array.Empty <Migration>();
                migrationsToRevert = appliedMigrations
                                     .OrderByDescending(m => m.Key)
                                     .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider))
                                     .ToList();
                actualTargetMigration = null;
            }
            else
            {
                targetMigration   = _migrationsAssembly.GetMigrationId(targetMigration);
                migrationsToApply = unappliedMigrations
                                    .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) <= 0)
                                    .OrderBy(m => m.Key)
                                    .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider))
                                    .ToList();
                migrationsToRevert = appliedMigrations
                                     .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) > 0)
                                     .OrderByDescending(m => m.Key)
                                     .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider))
                                     .ToList();
                actualTargetMigration = appliedMigrations
                                        .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) == 0)
                                        .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider))
                                        .SingleOrDefault();
            }
        }
Beispiel #38
0
        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            string sidePatern = " | ";
            string userPatern = " -> ";

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

            var saveAllUsers = new List <string>();

            while (input != "Lumpawaroo")
            {
                if (input.Contains(sidePatern))
                {
                    string[] tokens = input
                                      .Split(new string[] { " | " }, StringSplitOptions.RemoveEmptyEntries)
                                      .ToArray();

                    string forseSide = tokens[0];

                    if (!result.ContainsKey(forseSide))
                    {
                        result.Add(forseSide, new List <string>());
                    }

                    string forseUser = tokens[1];

                    if (!saveAllUsers.Contains(forseUser))
                    {
                        result[forseSide].Add(forseUser);

                        saveAllUsers.Add(forseUser);
                    }
                }
                else if (input.Contains(userPatern))
                {
                    string[] tokens = input
                                      .Split(new string[] { " -> " }, StringSplitOptions.RemoveEmptyEntries)
                                      .ToArray();
                    string forseSide = tokens[1];

                    string forseUser = tokens[0];

                    if (!result.ContainsKey(forseSide))
                    {
                        result.Add(forseSide, new List <string>());
                    }

                    if (saveAllUsers.Contains(forseUser))
                    {
                        string getKey = GetKey(result, forseUser);

                        result[getKey].Remove(forseUser);
                    }
                    result[forseSide].Add(forseUser);

                    Console.WriteLine($"{forseUser} joins the {forseSide} side!");
                }

                input = Console.ReadLine();
            }

            result = result.Where(x => x.Value.Count > 0).ToDictionary(k => k.Key, v => v.Value);


            foreach (var datas in result.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key))
            {
                string side = datas.Key;

                var users = datas.Value;

                Console.WriteLine($" Side: {side}, Members: {users.Count}");

                foreach (var user in users.OrderBy(x => x))
                {
                    Console.WriteLine($"! {user}");
                }
            }
        }
Beispiel #39
0
        // Driver
        public void Go()
        {
            // Input keys (use only 'a'
            // through 'z' and lower case)
            string rline;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader("words.txt");
            List <String>          keys = new List <string>();

            while ((rline = file.ReadLine()) != null)
            {
                keys.Add(rline);
            }
            //using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"C:\Users\Brett\Desktop\dict.txt"))
            //{
            //    while ((rline = file.ReadLine()) != null)
            //    {
            //        keys.Add(rline);
            //        if (!rline.Contains("&"))
            //        {
            //            file2.WriteLine(rline.ToLower());
            //        }
            //    }
            //}

            root = new TrieNode();
            // Construct trie
            int i;

            for (i = 0; i < keys.Count; i++)
            {
                insert(keys[i]);
            }

            //keys = null;
            string line = "";

            found = new Dictionary <string, int>();
            do
            {
                //read a complete line
                char c = Console.ReadKey().KeyChar;
                found.Clear();
                //check if line is empty or not
                if (c == '\r')
                {
                    addWeight(line);
                    Console.Clear();
                    Console.WriteLine("Searching: ");
                    line = "";
                }
                else if (Char.IsLetter(c))
                {
                    line += c.ToString();
                    searchAll(line);
                    var test = found;
                    Console.Clear();
                    Console.WriteLine("Searching: " + line);
                    Console.WriteLine(found.Count + " found");
                    int count = 0;
                    foreach (var item in found.OrderByDescending(x => x.Value))
                    {
                        if (count == 20)
                        {
                            break;
                        }
                        string ln = item.Key;
                        if (item.Value > 0)
                        {
                            ln += " (suggested)";
                        }
                        Console.WriteLine(ln);
                        count++;
                    }
                    //Console.Write("Line was = " + line);
                }
            } while (line != null);
        }
Beispiel #40
0
        public static object Answer(string[] inputs)
        {
            List <(DateTime TimeStamp, string Information)> guards_records = new List <(DateTime TimeStamp, string Information)>();

            foreach (var timestamp in inputs)
            {
                string   ts_str = timestamp.Substring(1, 16);
                string   infos  = timestamp.Substring(19, timestamp.Length - 19);
                DateTime ts     = DateTime.ParseExact(ts_str, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                guards_records.Add((ts, infos));
            }

            guards_records = guards_records.OrderBy(x => x.TimeStamp).ToList();

            int      guard       = 0;
            DateTime asleepStart = new DateTime();
            Dictionary <int, List <DateTime> > SleepyGuards = new Dictionary <int, List <DateTime> >();

            foreach (var(TimeStamp, Information) in guards_records)
            {
                if (IsWakingUp(Information))
                {
                    TimeSpan span = TimeStamp.Subtract(asleepStart);
                    for (int i = 0; i < span.TotalMinutes; i++)
                    {
                        if (SleepyGuards.ContainsKey(guard))
                        {
                            SleepyGuards[guard].Add(asleepStart.AddMinutes(i));
                        }
                        else
                        {
                            SleepyGuards.Add(guard, new List <DateTime>()
                            {
                                asleepStart.AddMinutes(i)
                            });
                        }
                    }
                    continue;
                }

                if (IsFallingAsleep(Information))
                {
                    asleepStart = TimeStamp;
                    continue;
                }

                if (IsBeginningShift(Information))
                {
                    guard = GetGuardID(Information);
                    continue;
                }
            }

            var sleepiestGuard = SleepyGuards.OrderByDescending(i => i.Value.Count()).FirstOrDefault();

            var sleepiestGuardGrouped = sleepiestGuard.Value.GroupBy(x => x.Minute).ToList()
                                        .OrderByDescending(x => x.Count())
                                        .FirstOrDefault();


            var partTwoAnswer = PartTwo(SleepyGuards);

            return($"Part 1 : Guard #{sleepiestGuard.Key} likes to sleep at {sleepiestGuardGrouped.Key} min " +
                   $": {sleepiestGuard.Key} x {sleepiestGuardGrouped.Key} = {sleepiestGuard.Key * sleepiestGuardGrouped.Key} \n{partTwoAnswer}");
        }
Beispiel #41
0
        static void Main(string[] args)
        {
            string[] participants = Console.ReadLine()
                                    .Split(',')
                                    .Select(n => n.Trim())
                                    .ToArray();

            string[] songs = Console.ReadLine()
                             .Split(',')
                             .Select(n => n.Trim())
                             .ToArray();

            var participantAwardsDict = new Dictionary <string, HashSet <string> >();

            string inputLine = Console.ReadLine();

            while (inputLine != "dawn")
            {
                string[] inputParameters = inputLine
                                           .Split(',')
                                           .Select(n => n.Trim())
                                           .ToArray();

                string participant = inputParameters[0];
                string song        = inputParameters[1];
                string award       = inputParameters[2];

                if (songs.Contains(song) && participants.Contains(participant))
                {
                    if (!participantAwardsDict.ContainsKey(participant))
                    {
                        participantAwardsDict[participant] = new HashSet <string>();
                    }

                    participantAwardsDict[participant].Add(award);
                }

                inputLine = Console.ReadLine();
            }

            if (!participantAwardsDict.Any())
            {
                Console.WriteLine("No awards");
            }
            else
            {
                participantAwardsDict = participantAwardsDict
                                        .OrderByDescending(n => n.Value.Count)
                                        .ThenBy(n => n.Key)
                                        .ToDictionary(n => n.Key, n => n.Value);

                foreach (var participantAwardPair in participantAwardsDict)
                {
                    string           participant = participantAwardPair.Key;
                    HashSet <string> awards      = participantAwardPair.Value;

                    Console.WriteLine($"{participant}: {awards.Count} awards");

                    foreach (var award in awards.OrderBy(a => a))
                    {
                        Console.WriteLine($"--{award}");
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            string comand = Console.ReadLine();
            Dictionary <string, Dictionary <string, int> > trains = new Dictionary <string, Dictionary <string, int> >();

            while (comand != "It's Training Men!")
            {
                string[] info = comand.Split(' ');
                if (info.Length == 5)
                {
                    string name  = info[0];
                    string wagon = info[2];
                    int    power = int.Parse(info[4]);
                    if (!trains.ContainsKey(name))
                    {
                        Dictionary <string, int> current = new Dictionary <string, int>();
                        current.Add(wagon, power);
                        trains.Add(name, current);
                    }
                    else
                    {
                        if (!trains[name].ContainsKey(wagon))
                        {
                            trains[name].Add(wagon, power);
                        }
                    }
                }
                else if (info[1] == "->")
                {
                    string firs  = info[0];
                    string other = info[2];
                    if (!trains.ContainsKey(firs))
                    {
                        Dictionary <string, int> current = new Dictionary <string, int>();
                        trains.Add(firs, current);
                    }
                    foreach (var pair in trains[other])
                    {
                        trains[firs].Add(pair.Key, pair.Value);
                    }
                    trains.Remove(other);
                }
                else
                {
                    string firs  = info[0];
                    string other = info[2];
                    if (!trains.ContainsKey(firs))
                    {
                        Dictionary <string, int> current = new Dictionary <string, int>();
                        trains.Add(firs, current);
                    }
                    trains[firs].Clear();
                    foreach (var pair in trains[other])
                    {
                        trains[firs].Add(pair.Key, pair.Value);
                    }
                }

                comand = Console.ReadLine();
            }
            foreach (var train in trains.OrderByDescending(x => x.Value.Values.Sum()).ThenBy(x => x.Value.Values.Count))
            {
                Console.WriteLine($"Train: {train.Key}");
                foreach (var item in train.Value.OrderByDescending(x => x.Value))
                {
                    Console.WriteLine($"###{item.Key} - {item.Value}");
                }
            }
        }
Beispiel #43
0
        public List <string> GetAnchorWords(int N)
        {
            StringBuilder sbAllWords = new StringBuilder();

            foreach (children child in children)
            {
                sbAllWords.Append(child.SubtreeText);
                sbAllWords.Append(" ");
            }
            string[] allWords = GetAllWords(sbAllWords.ToString());
            Dictionary <string, string> stemParentDictionary = GetStemParentDictionary(allWords);
            List <string>         anchorWords  = new List <string>();
            children              rootNode     = new children();
            List <HashSet <int> > rootChildIDs = new List <HashSet <int> >();

            foreach (children child in children)
            {
                GetChildIDHashSetList(child);
                HashSet <int> currChildIDs = new HashSet <int>();
                currChildIDs.Add(child.id);
                foreach (var item in child.ChildIDList)
                {
                    currChildIDs.UnionWith(item);
                }
                rootChildIDs.Add(currChildIDs);
            }
            rootNode.ChildIDList = rootChildIDs;
            NodeList             = new List <children>();
            NodeList.Add(rootNode);
            foreach (children child in children)
            {
                PopulateNodeList(child);
            }
            Dictionary <string, HashSet <int> > wordIDMapping = GetWordIDMapping();
            //Dictionary<string, double> WordTreeScore = new Dictionary<string, double>();
            Dictionary <string, List <children> > WordLCAList = new Dictionary <string, List <children> >();

            foreach (var kvp in wordIDMapping)
            {
                List <children> currLCAList = new List <children>();
                int             numLCAs     = 0;
                foreach (children node in NodeList)
                {
                    int numBranchesWithWord = 0;
                    foreach (var childIDBranch in node.ChildIDList)
                    {
                        if (childIDBranch.Intersect(kvp.Value).Count() > 0)
                        {
                            numBranchesWithWord += 1;
                        }
                    }
                    if ((numBranchesWithWord == 1 && node.ChildIDList.Count == 1) || numBranchesWithWord > 1)
                    {
                        currLCAList.Add(node);
                    }
                }
                WordLCAList[stemParentDictionary.ContainsKey(kvp.Key)? stemParentDictionary[kvp.Key]:kvp.Key] = currLCAList;
            }
            anchorWords = WordLCAList
                          .OrderByDescending(x => x.Value.Count)
                          .Select(x => x.Key)
                          .Where(y => CommonWords.GetFrequency(y) < 20)
                          .Where(z => !(z.EndsWith("n't") || z.EndsWith("'m") || (z.EndsWith("'ll")) || (z.EndsWith("'d")) || z.EndsWith("'ve") || z.EndsWith("'re") || z.EndsWith("'s")))
                          .Take(N)
                          .ToList();
            return(anchorWords);
        }
Beispiel #44
0
    public static void Main()

    {
        int boardSize = int.Parse(Console.ReadLine());

        char[,] chessBoard = new char[boardSize, boardSize];



        FillInTheBoard(chessBoard, boardSize);



        List <int[]> possibleMoves = new List <int[]>

        {
            new[] { -1, -2 },

            new[] { -1, 2 },

            new[] { 1, -2 },

            new[] { 1, 2 },

            new[] { -2, -1 },

            new[] { -2, 1 },

            new[] { 2, -1 },

            new[] { 2, 1 }
        };



        Dictionary <string, int> attackingKinghts = CollectAttackingKnights(chessBoard, possibleMoves);

        int removedKnights = 0;



        while (attackingKinghts.Count > 0)

        {
            KeyValuePair <string, int> mostDangerousKnight = attackingKinghts.OrderByDescending(x => x.Value).First();

            int[] coordinates = mostDangerousKnight.Key

                                .Split('|')

                                .Select(int.Parse)

                                .ToArray();

            chessBoard[coordinates[0], coordinates[1]] = '0';

            RemoveAttackingKnight(attackingKinghts, possibleMoves, coordinates);

            removedKnights++;
        }



        Console.WriteLine(removedKnights);
    }
Beispiel #45
0
    public static void Main()
    {
        long bagCapacity = long.Parse(Console.ReadLine());

        var input    = Console.ReadLine().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        var sequence = new Queue <string>(input);

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

        bagQuantites["Gold"] = 0;
        bagItems["Gold"]     = new Dictionary <string, int>();
        bagQuantites["Gem"]  = 0;
        bagItems["Gem"]      = new Dictionary <string, int>();
        bagQuantites["Cash"] = 0;
        bagItems["Cash"]     = new Dictionary <string, int>();

        while (sequence.Count > 0)
        {
            var item     = sequence.Dequeue();
            var quantity = int.Parse(sequence.Dequeue());
            if (bagQuantites.Sum(i => i.Value) + quantity > bagCapacity)
            {
                break;
            }

            if (item.Equals("gold", StringComparison.InvariantCultureIgnoreCase))
            {
                bagQuantites["Gold"] += quantity;
                if (!bagItems["Gold"].ContainsKey("Gold"))
                {
                    bagItems["Gold"]["Gold"] = 0;
                }

                bagItems["Gold"]["Gold"] += quantity;
            }
            else if (item.Length == 3)
            {
                if (bagQuantites["Cash"] + quantity <= bagQuantites["Gem"])
                {
                    bagQuantites["Cash"] += quantity;
                    bagItems["Cash"].Add(item, quantity);
                }
            }
            else if (item.ToLower().Contains("gem"))
            {
                if (bagQuantites["Gem"] + quantity <= bagQuantites["Gold"])
                {
                    bagQuantites["Gem"] += quantity;
                    bagItems["Gem"].Add(item, quantity);
                }
            }
        }

        foreach (var kvp in bagQuantites.OrderByDescending(i => i.Value))
        {
            if (kvp.Value > 0)
            {
                Console.WriteLine($"<{kvp.Key}> ${kvp.Value}");

                foreach (var item in bagItems[kvp.Key].OrderByDescending(i => i.Key).ThenBy(i => i.Value))
                {
                    var itemName = kvp.Key.Equals("gold", StringComparison.InvariantCultureIgnoreCase) ? "Gold" : item.Key;
                    Console.WriteLine($"##{itemName} - {item.Value}");
                }
            }
        }
    }
        static void Main(string[] args)
        {
            Dictionary <string, Dictionary <string, int> > boys = new Dictionary <string, Dictionary <string, int> >();
            string command = Console.ReadLine();

            while (command != "Make a decision already!")
            {
                string[] info = command.Split(' ');
                if (command.EndsWith("does Gyubek!"))
                {
                    string name = command.Substring(0, command.IndexOf(' '));

                    if (boys.ContainsKey(name))
                    {
                        if (boys[name].Values.Any(x => x > 0))
                        {
                            boys[name].Clear();
                        }
                    }
                }
                else
                {
                    string name  = info[0];
                    string trait = info[1];
                    int    value = int.Parse(info[2]);
                    if (!boys.ContainsKey(name))
                    {
                        Dictionary <string, int> current = new Dictionary <string, int>();
                        int newValue = GetChange(trait, value);
                        current.Add(trait, newValue);
                        boys.Add(name, current);
                    }
                    else
                    {
                        if (!boys[name].ContainsKey(trait))
                        {
                            int newValue = GetChange(trait, value);
                            boys[name].Add(trait, newValue);
                        }
                        else
                        {
                            if (boys[name][trait] < value)
                            {
                                boys[name][trait] = GetChange(trait, value);
                            }
                        }
                    }
                }

                command = Console.ReadLine();
            }
            foreach (var pair in boys.OrderByDescending(x => x.Value.Values.Sum()).ThenBy(x => x.Key))
            {
                Console.WriteLine("# {0}: {1}", pair.Key, pair.Value.Values.Sum());
                foreach (var item in pair.Value.OrderByDescending(x => x.Value))
                {
                    Console.WriteLine("!!! {0} -> {1}", item.Key, item.Value);
                }
            }
            Console.WriteLine();
        }
Beispiel #47
0
        private void btnRandomNumberRatios_Click(object sender, RoutedEventArgs e)
        {
            //here we are initilizating the variable. until here it is null
            dicNumbers = new Dictionary <int, int>();

            Random myrandGenerator = new Random();

            for (int i = 0; i < 1000000; i++)
            {
                //this will generate a random number between 1 and 101 [1,2,3,4...100]
                int irMyRandNumber = myrandGenerator.Next(1, 101);

                if (dicNumbers.ContainsKey(irMyRandNumber))
                {
                    dicNumbers[irMyRandNumber]++; // equals to dicNumbers[irMyRandNumber] = dicNumbers[irMyRandNumber]+1;
                    // equals to dicNumbers[irMyRandNumber]+=1;
                }
                else
                {
                    dicNumbers.Add(irMyRandNumber, 1);
                }
            }

            dicNumbers = dicNumbers.OrderBy(pr => pr.Key).ToDictionary(pr => pr.Key, pr => pr.Value);
            Dictionary <int, int> dicBigToSmall = dicNumbers.OrderByDescending(pr => pr.Key).ToDictionary(pr => pr.Key, pr => pr.Value);

            File.WriteAllLines("ordered by ascending.txt", dicNumbers.Select(pr => pr.Key + "\t" + pr.Value));

            using (StreamWriter swWrite = new StreamWriter("ordered by ascending 2.txt"))
            {
                foreach (var vrKeyAndValue in dicNumbers)
                {
                    swWrite.WriteLine(vrKeyAndValue.Key + "\t" + vrKeyAndValue.Value);
                }
            }

            File.Delete("ordered by ascending 3.txt");
            var vrNumbersList = dicNumbers.ToList();

            for (int i = 0; i < dicNumbers.Count; i++)
            {
                File.AppendAllText("ordered by ascending 3.txt",
                                   vrNumbersList[i].Key + "\t" + vrNumbersList[i].Value + Environment.NewLine);
            }

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

            using (StreamReader swRead = new StreamReader("ordered by ascending.txt"))
            {
                while (true)
                {
                    var vrLine = swRead.ReadLine();
                    if (vrLine == null)
                    {
                        break;
                    }

                    string srKeyLine = vrLine.Split('\t').First();
                    //string srKeyLine = vrLine.Split('\t')[0];

                    string srValueLine = vrLine.Split('\t').Last();
                    //string srValueLine = vrLine.Split('\t')[1];

                    int irKey = Convert.ToInt32(srKeyLine);
                    //int irKey = Int32.Parse(srKeyLine);

                    int irVal = Convert.ToInt32(srValueLine);

                    ReaderDict.Add(irKey, irVal);
                }
            }

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

            foreach (var vrLine in File.ReadLines("ordered by ascending.txt"))
            {
                string srKeyLine = vrLine.Split('\t').First();

                string srValueLine = vrLine.Split('\t').Last();

                int irKey = Convert.ToInt32(srKeyLine);

                int irVal = Convert.ToInt32(srValueLine);

                ReaderDict.Add(irKey, irVal);
            }
        }
Beispiel #48
0
        static void Main(string[] args)
        {
            string[] keyMaterialsNames = new string[]
            {
                "shards",
                "fragments",
                "motes"
            };

            string itemObtained = string.Empty;

            bool obtained = false;

            Dictionary <string, long> keyMaterials = new Dictionary <string, long>();

            Dictionary <string, long> junk = new Dictionary <string, long>();

            keyMaterials["shards"]    = 0;
            keyMaterials["fragments"] = 0;
            keyMaterials["motes"]     = 0;

            while (!obtained)
            {
                string[] inputArgs = Console.ReadLine()
                                     .Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                     .ToArray();

                for (int i = 0; i < inputArgs.Length; i += 2)
                {
                    long   qty      = long.Parse(inputArgs[i]);
                    string material = inputArgs[i + 1].ToLower();

                    if (keyMaterialsNames.Contains(material))
                    {
                        keyMaterials[material] += qty;

                        if (keyMaterials.Any(m => m.Value >= 250))
                        {
                            if (material == "shards")
                            {
                                itemObtained = "Shadowmourne";
                            }
                            else if (material == "fragments")
                            {
                                itemObtained = "Valanyr";
                            }
                            else
                            {
                                itemObtained = "Dragonwrath";
                            }

                            keyMaterials[material] -= 250;

                            obtained = true;
                            break;
                        }
                    }
                    else
                    {
                        AddJunk(junk, qty, material);
                    }
                }
            }

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

            keyMaterials = keyMaterials
                           .OrderByDescending(kvp => kvp.Value)
                           .ThenBy(kvp => kvp.Key)
                           .ToDictionary(a => a.Key, b => b.Value);

            foreach (var kvp in keyMaterials)
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value}");
            }

            junk = junk
                   .OrderBy(kvp => kvp.Key)
                   .ToDictionary(a => a.Key, b => b.Value);

            foreach (var kvp in junk)
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value}");
            }
        }
Beispiel #49
0
        static void Main(string[] args)
        {
            Dictionary <string, int> materials = new Dictionary <string, int>();

            materials["shards"]    = 0;
            materials["fragments"] = 0;
            materials["motes"]     = 0;

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

            string input = Console.ReadLine().ToLower();

            Regex patter = new Regex(@"(([0-9]+)(?:\s)([\w-]+))");

            string legendary = string.Empty;

            while (true)
            {
                MatchCollection matches = patter.Matches(input);

                bool found = false;
                foreach (Match match in matches)
                {
                    int    quantity = int.Parse(match.Groups[2].Value);
                    string material = match.Groups[3].Value;

                    if (materials.ContainsKey(material))
                    {
                        materials[material] += quantity;
                    }
                    else if (!junk.ContainsKey(material))
                    {
                        junk.Add(material, quantity);
                    }
                    else
                    {
                        junk[material] += quantity;
                    }

                    if (materials["shards"] >= 250 ||
                        materials["fragments"] >= 250 ||
                        materials["motes"] >= 250)
                    {
                        legendary = material.Equals("shards") ? "Shadowmourne"
                                    : material.Equals("fragments") ? "Valanyr"
                                    : "Dragonwrath";

                        materials[material] -= 250;

                        found = true;

                        break;
                    }
                }

                if (found)
                {
                    break;
                }

                input = Console.ReadLine().ToLower();
            }

            Console.WriteLine("{0} obtained!", legendary);

            foreach (KeyValuePair <string, int> item in
                     materials.OrderByDescending(x => x.Value)
                     .ThenBy(x => x.Key))
            {
                Console.WriteLine("{0}: {1}"
                                  , item.Key
                                  , item.Value);
            }
            foreach (KeyValuePair <string, int> item in
                     junk.OrderBy(x => x.Key))
            {
                Console.WriteLine("{0}: {1}"
                                  , item.Key
                                  , item.Value);
            }
        }
Beispiel #50
0
        static void Main(string[] args)
        {
            var dict            = new Dictionary <string, Dictionary <string, int> >();
            var name            = "";
            var otherName       = "";
            var role            = "";
            var stats           = 0;
            var statsToRemember = 0;
            var allRoles        = "";

            while (true)
            {
                string[] input = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (input[0] == "Ave")
                {
                    break;
                }
                if (input.Length == 5)
                {
                    name            = input[0];
                    role            = input[2];
                    allRoles       += role + " ";
                    stats           = int.Parse(input[4]);
                    statsToRemember = stats;
                    if (!dict.ContainsKey(name))
                    {
                        dict.Add(name, new Dictionary <string, int>());
                    }
                    dict[name].Add(role, stats);
                    if (dict[name].ContainsKey(role))
                    {
                        if (stats > statsToRemember)
                        {
                            dict[name][role] = stats;
                        }
                    }
                }
                else
                {
                    name      = input[0];
                    otherName = input[2];
                    if (dict.ContainsKey(name) && dict.ContainsKey(otherName))
                    {
                        if (dict.Keys.Contains(otherName))
                        {
                            var nameOneBool   = false;
                            var roleToFight   = "";
                            var splittedRoles = allRoles.Split();
                            for (int i = 0; i < splittedRoles.Length; i++)
                            {
                                if (dict[name].ContainsKey(splittedRoles[i]) && dict[otherName].ContainsKey(splittedRoles[i]))
                                {
                                    nameOneBool = true;
                                    roleToFight = splittedRoles[i];
                                }
                            }
                            if (nameOneBool && dict[name][roleToFight] > dict[otherName][roleToFight])
                            {
                                dict.Remove(otherName);
                            }
                            else if (nameOneBool && dict[name][roleToFight] < dict[otherName][roleToFight])
                            {
                                dict.Remove(name);
                            }
                        }
                    }
                }
            }
            foreach (var item in dict.OrderByDescending(x => x.Value.Values.Sum()).ThenBy(x => x.Key))
            {
                Console.WriteLine($"{item.Key}: {item.Value.Values.Sum()} skill");
                foreach (var kvp in item.Value.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
                {
                    Console.WriteLine($"- {kvp.Key} <!> {kvp.Value}");
                }
            }
        }
Beispiel #51
0
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            Dictionary <string, List <int> > heroes = new Dictionary <string, List <int> >();

            for (int i = 0; i < n; i++)
            {
                string[] insertHeroes = Console.ReadLine().Split();
                heroes.Add(insertHeroes[0], new List <int>());
                heroes[insertHeroes[0]].Add(int.Parse(insertHeroes[1]));
                heroes[insertHeroes[0]].Add(int.Parse(insertHeroes[2]));
            }

            string[] cmdArgs = Console.ReadLine().Split(" - ");

            while (cmdArgs[0] != "End")
            {
                string command  = cmdArgs[0];
                string heroName = cmdArgs[1];

                int heroHP = heroes[heroName][0];
                int heroMP = heroes[heroName][1];

                if (command == "CastSpell")
                {
                    int    mpNeeded  = int.Parse(cmdArgs[2]);
                    string spellName = cmdArgs[3];

                    if (heroes.ContainsKey(heroName))
                    {
                        if (heroMP >= mpNeeded)
                        {
                            heroes[heroName][1] -= mpNeeded;
                            Console.WriteLine($"{heroName} has successfully cast {spellName} and now has {heroes[heroName][1]} MP!");
                        }
                        else
                        {
                            Console.WriteLine($"{heroName} does not have enough MP to cast {spellName}!");
                        }
                    }
                }

                else if (command == "TakeDamage")
                {
                    int    damage   = int.Parse(cmdArgs[2]);
                    string attacker = cmdArgs[3];

                    heroes[heroName][0] -= damage;

                    if (heroes[heroName][0] > 0)
                    {
                        Console.WriteLine($"{heroName} was hit for {damage} HP by {attacker} and now has {heroes[heroName][0]} HP left!");
                    }
                    else
                    {
                        heroes.Remove(heroName);
                        Console.WriteLine($"{heroName} has been killed by {attacker}!");
                    }
                }

                else if (command == "Recharge")
                {
                    int amount = int.Parse(cmdArgs[2]);
                    heroes[heroName][1] += amount;

                    if (heroes[heroName][1] > 200)
                    {
                        int rechargedFor = amount - (heroes[heroName][1] - 200);
                        Console.WriteLine($"{heroName} recharged for {rechargedFor} MP!");

                        heroes[heroName][1] = 200;
                    }
                    else
                    {
                        Console.WriteLine($"{heroName} recharged for {amount} MP!");
                    }
                }

                else if (command == "Heal")
                {
                    int amount = int.Parse(cmdArgs[2]);
                    heroes[heroName][0] += amount;

                    if (heroes[heroName][0] > 100)
                    {
                        int healedFor = amount - (heroes[heroName][0] - 100);

                        Console.WriteLine($"{heroName} healed for {healedFor} HP!");
                        heroes[heroName][0] = 100;
                    }
                    else
                    {
                        Console.WriteLine($"{heroName} healed for {amount} HP!");
                    }
                }

                cmdArgs = Console.ReadLine().Split(" - ");
            }

            foreach (var item in heroes.OrderByDescending(h => h.Value[0]).ThenBy(h => h.Key))
            {
                Console.WriteLine($"{item.Key}");
                Console.WriteLine($"  HP: {item.Value[0]}");
                Console.WriteLine($"  MP: {item.Value[1]}");
            }
        }
Beispiel #52
0
        static void Main(string[] args)
        {
            var teams = new Dictionary <string, List <long> >();

            string key     = Console.ReadLine();
            string command = Console.ReadLine();

            while (command != "final")
            {
                string[] tokens = command
                                  .Split(' ');
                string teamA      = tokens[0];
                int    startIndex = teamA.IndexOf(key);
                int    endIndex   = teamA.LastIndexOf(key);
                string homeTeam   = teamA
                                    .Substring(startIndex + key.Length, endIndex - startIndex - key.Length);
                char[] homeTeamArray = homeTeam.ToUpper().ToCharArray();
                Array.Reverse(homeTeamArray);
                homeTeam = new string(homeTeamArray);

                string teamB = tokens[1];
                startIndex = teamB.IndexOf(key);
                endIndex   = teamB.LastIndexOf(key);
                string awayTeam = teamB
                                  .Substring(startIndex + key.Length, endIndex - startIndex - key.Length);
                char[] awayTeamArray = awayTeam.ToUpper().ToCharArray();
                Array.Reverse(awayTeamArray);
                awayTeam = new string(awayTeamArray);

                long[] goals = tokens[2]
                               .Split(':')
                               .Select(long.Parse)
                               .ToArray();
                long homeTeamGoals = goals[0];
                long awayTeamGoals = goals[1];

                long pointsForHomeTeam;
                long pointsForAwayTeam;

                if (homeTeamGoals > awayTeamGoals)
                {
                    pointsForHomeTeam = 3;
                    pointsForAwayTeam = 0;
                }
                else if (homeTeamGoals < awayTeamGoals)
                {
                    pointsForHomeTeam = 0;
                    pointsForAwayTeam = 3;
                }
                else
                {
                    pointsForHomeTeam = 1;
                    pointsForAwayTeam = 1;
                }

                if (teams.ContainsKey(homeTeam))
                {
                    teams[homeTeam][0] += pointsForHomeTeam;
                    teams[homeTeam][1] += homeTeamGoals;
                }
                else
                {
                    teams[homeTeam] = new List <long>();
                    teams[homeTeam].Add(pointsForHomeTeam);
                    teams[homeTeam].Add(homeTeamGoals);
                }

                if (teams.ContainsKey(awayTeam))
                {
                    teams[awayTeam][0] += pointsForAwayTeam;
                    teams[awayTeam][1] += awayTeamGoals;
                }
                else
                {
                    teams[awayTeam] = new List <long>();
                    teams[awayTeam].Add(pointsForAwayTeam);
                    teams[awayTeam].Add(awayTeamGoals);
                }

                command = Console.ReadLine();
            }

            Console.WriteLine("League standings:");
            int count = 1;

            foreach (var pair in teams
                     .OrderByDescending(x => x.Value[0])
                     .ThenBy(t => t.Key))
            {
                string name   = pair.Key;
                long   points = pair.Value[0];

                Console.WriteLine($"{count}. {name} {points}");

                count++;
            }

            Console.WriteLine("Top 3 scored goals:");

            foreach (var pair in teams
                     .OrderByDescending(x => x.Value[1])
                     .ThenBy(x => x.Key)
                     .Take(3))
            {
                string name  = pair.Key;
                long   goals = pair.Value[1];

                Console.WriteLine($"- {name} -> {goals}");
            }
        }
Beispiel #53
0
        static void Main(string[] args)
        {
            string legendaryItem = String.Empty;
            Dictionary <string, int> materials = new Dictionary <string, int>();

            materials.Add("motes", 0);
            materials.Add("shards", 0);
            materials.Add("fragments", 0);
            Dictionary <string, int> junk = new Dictionary <string, int>();

            while (materials["motes"] < 250 && materials["fragments"] < 250 && materials["shards"] < 250)
            {
                string   input       = Console.ReadLine().ToLower();
                string[] inputTokens = input.Split(" ");
                for (int i = 0; i < inputTokens.Length; i += 2)
                {
                    int    quantity = int.Parse(inputTokens[i]);
                    string material = inputTokens[i + 1];

                    switch (material)
                    {
                    case "shards":
                    case "fragments":
                    case "motes":
                        materials[material] += quantity;
                        break;

                    default:
                        if (!junk.ContainsKey(material))
                        {
                            junk.Add(material, 0);
                        }
                        junk[material] += quantity;
                        break;
                    }

                    if (materials["shards"] >= 250 || materials["fragments"] >= 250 || materials["motes"] >= 250)
                    {
                        break;
                    }
                }
            }

            if (materials["shards"] >= 250)
            {
                legendaryItem        = "Shadowmourne";
                materials["shards"] -= 250;
            }
            else if (materials["fragments"] >= 250)
            {
                legendaryItem           = "Valanyr";
                materials["fragments"] -= 250;
            }
            else
            {
                legendaryItem       = "Dragonwrath";
                materials["motes"] -= 250;
            }

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

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

            foreach (var item in junk.OrderBy(entry => entry.Key))
            {
                Console.WriteLine($"{item.Key}: {item.Value}");
            }
        }
Beispiel #54
0
        /// <remarks>
        /// This has just been copied with slight modification from PagesController and
        /// needs to be refactored.
        /// </remarks>
        public IEnumerable <PageSearchResult> Execute(SearchPagesQuery query, IExecutionContext executionContext)
        {
            if (string.IsNullOrWhiteSpace(query.Text))
            {
                yield break;
            }

            var isAuthenticated = executionContext.UserContext.UserId.HasValue;

            // TODO: Search results should look at page titles as well as module content

            // Find any page versions that match by title
            // TODO: Ignore small words like 'of' and 'the'
            var titleMatchesPageVersions = _dbContext
                                           .Pages
                                           .Where(p => !p.IsDeleted &&
                                                  p.PageVersions.Any(pv => !pv.IsDeleted && isAuthenticated ? true : pv.WorkFlowStatusId == (int)WorkFlowStatus.Published) &&
                                                  !query.LocaleId.HasValue || p.LocaleId == query.LocaleId &&
                                                  p.PageTypeId == (int)PageType.Generic
                                                  )
                                           .Select(p => p.PageVersions
                                                   .OrderByDescending(v => v.CreateDate)
                                                   .First(pv => !pv.IsDeleted && isAuthenticated ? true : pv.WorkFlowStatusId == (int)WorkFlowStatus.Published)
                                                   )
                                           .ToList()
                                           .Where(v => v.Title.Contains(query.Text) ||
                                                  v.Title.ToLower().Split(new char[] { ' ' }).Intersect(query.Text.ToLower().Split(new char[] { ' ' })).Any()
                                                  )
            ;


            // TODO: Search should split the search term and lookup individual words as well (and rank them less strongly)

            // Get a list of ALL the page modules for live pages - we'll search through these for any matches
            var pageModules = _dbContext
                              .PageVersionModules
                              .Include(m => m.PageModuleType)
                              .Where(m => !m.PageVersion.IsDeleted)
                              .Where(m => !m.PageVersion.Page.IsDeleted)
                              .Where(m => isAuthenticated ? true : m.PageVersion.WorkFlowStatusId == (int)WorkFlowStatus.Published)
                              .Where(m => !query.LocaleId.HasValue || m.PageVersion.Page.LocaleId == query.LocaleId)
                              .Where(m => m.PageVersion.Page.PageTypeId == (int)PageType.Generic)
                              .ToList();

            // This will store a list of matches for each module
            var matches = new Dictionary <PageVersionModule, List <string> >();

            foreach (var pageModule in pageModules.Where(p => !string.IsNullOrEmpty(query.Text)))
            {
                var  dataProvider     = _moduleDisplayDataFactory.MapDisplayModel(pageModule.PageModuleType.FileName, pageModule, WorkFlowStatusQuery.Published);
                Type dataProviderType = dataProvider.GetType();

                // If this module is searchable - ie there is content to search
                // TODO: Module Searching
                //if (dataProvider is ISearchable)
                //{
                var props = dataProviderType.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(SearchableAttribute)));

                foreach (var prop in props)
                {
                    string str = _htmlSanitizer.StripHtml(((string)prop.GetValue(dataProvider, null)));

                    if (str.IndexOf(query.Text ?? "", StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        if (!matches.ContainsKey(pageModule))
                        {
                            matches[pageModule] = new List <string>();
                        }

                        int index = str.ToLower().IndexOf(query.Text.ToLower());

                        int startIndex = index - 100;
                        while (startIndex < 0)
                        {
                            startIndex++;
                        }

                        int length = (index - startIndex) + query.Text.Length + 100;
                        while ((startIndex + length) > str.Length)
                        {
                            length--;
                        }

                        var matchStr = str.Substring(startIndex, length);

                        // Stop the string at the last space
                        if ((startIndex + length) < str.Length - 1 && matchStr.LastIndexOf(" ") > -1)
                        {
                            matchStr = matchStr.Substring(0, matchStr.LastIndexOf(" ")) + " &hellip;";
                        }

                        // Stop the string at the first space
                        if (startIndex > 0 && matchStr.IndexOf(" ") > -1)
                        {
                            matchStr = "&hellip; " + matchStr.Substring(matchStr.IndexOf(" ") + 1);
                        }

                        // Highlight the search term
                        matchStr = Regex.Replace(matchStr, query.Text, @"<b>$0</b>", RegexOptions.IgnoreCase);

                        matches[pageModule].Add(matchStr);
                    }
                }
                //}
            }

            // This is a list of pageversions matches to the number of matches
            var pageVersionMatches = matches
                                     .OrderByDescending(m => m.Value.Count)
                                     .GroupBy(m => m.Key.PageVersion.PageVersionId)
                                     .ToDictionary(
                g => g.First().Key.PageVersion,
                g => g.First().Value.Select(m => (IHtmlString) new HtmlString(m))
                );

            // Add any pages matched by title to the list of matches
            foreach (var pageVersion in titleMatchesPageVersions)
            {
                if (!pageVersionMatches.ContainsKey(pageVersion))
                {
                    pageVersionMatches.Add(pageVersion, null);
                }
            }

            var searchResults = new List <PageSearchResult>();
            var pageroutes    = _queryExecutor.GetAll <PageRoute>();

            foreach (var pageVersionMatch in pageVersionMatches
                     .OrderByDescending(m => titleMatchesPageVersions.Contains(m.Key))
                     .ThenByDescending(m => m.Value == null ? 0 : m.Value.Count()))
            {
                var version = pageVersionMatch.Key;
                var route   = pageroutes.SingleOrDefault(r => r.PageId == version.PageId);

                if (route != null)
                {
                    var result = new PageSearchResult();
                    result.FoundText = pageVersionMatch.Value == null ? new HtmlString(version.MetaDescription) : pageVersionMatch.Value.First();
                    result.Title     = version.Title;
                    result.Url       = route.FullPath;

                    yield return(result);
                }
            }
        }
        public void update(long counter)
        {
            var timeWarpFixedDeltaTime = TimeWarpFixedDeltaTime;

            IsUpdatedAtLeastOnce = true;
            Counter = counter;

            stored_supply                = currentPowerSupply;
            stored_stable_supply         = stable_supply;
            stored_resource_demand       = current_resource_demand;
            stored_current_demand        = current_resource_demand;
            stored_current_hp_demand     = high_priority_resource_demand;
            stored_current_charge_demand = charge_resource_demand;
            stored_charge_demand         = charge_resource_demand;
            stored_total_power_supplied  = total_power_distributed;

            current_resource_demand       = 0;
            high_priority_resource_demand = 0;
            charge_resource_demand        = 0;
            total_power_distributed       = 0;

            double availableResourceAmount;
            double maxResouceAmount;

            my_part.GetConnectedResourceTotals(resourceDefinition.id, out availableResourceAmount, out maxResouceAmount);

            //if (maxResouceAmount > 0 && !double.IsNaN(maxResouceAmount) && !double.IsNaN(availableResourceAmount))
            //    resource_bar_ratio = availableResourceAmount / maxResouceAmount;
            //else
            //    resource_bar_ratio = 0.0001;

            double missingResourceAmount = maxResouceAmount - availableResourceAmount;

            currentPowerSupply += availableResourceAmount;

            double high_priority_demand_supply_ratio = high_priority_resource_demand > 0
                ? Math.Min((currentPowerSupply - stored_current_charge_demand) / stored_current_hp_demand, 1.0)
                : 1.0;

            double demand_supply_ratio = stored_current_demand > 0
                ? Math.Min((currentPowerSupply - stored_current_charge_demand - stored_current_hp_demand) / stored_current_demand, 1.0)
                : 1.0;

            //Prioritise supplying stock ElectricCharge resource
            if (resourceDefinition.id == megajouleResourceDefinition.id && stored_stable_supply > 0)
            {
                double amount;
                double maxAmount;

                my_part.GetConnectedResourceTotals(electricResourceDefinition.id, out amount, out maxAmount);
                double stock_electric_charge_needed = maxAmount - amount;

                double power_supplied = Math.Min(currentPowerSupply * 1000 * timeWarpFixedDeltaTime, stock_electric_charge_needed);
                if (stock_electric_charge_needed > 0)
                {
                    var deltaResourceDemand = stock_electric_charge_needed / 1000 / timeWarpFixedDeltaTime;
                    current_resource_demand += deltaResourceDemand;
                    charge_resource_demand  += deltaResourceDemand;
                }

                if (power_supplied > 0)
                {
                    double fixed_provided_electric_charge_in_MW = my_part.RequestResource(ResourceManager.STOCK_RESOURCE_ELECTRICCHARGE, -power_supplied) / 1000;
                    var    provided_electric_charge_per_second  = fixed_provided_electric_charge_in_MW / timeWarpFixedDeltaTime;
                    total_power_distributed += -provided_electric_charge_per_second;
                    currentPowerSupply      += provided_electric_charge_per_second;
                }
            }

            power_supply_list_archive = power_produced.OrderByDescending(m => m.Value.maximumSupply).ToList();

            // store current supply and update average
            power_supply_list_archive.ForEach(m =>
            {
                Queue <double> queue;

                if (!power_produced_history.TryGetValue(m.Key, out queue))
                {
                    queue = new Queue <double>(10);
                    power_produced_history.Add(m.Key, queue);
                }

                if (queue.Count > 10)
                {
                    queue.Dequeue();
                }
                queue.Enqueue(m.Value.currentSupply);

                m.Value.averageSupply = queue.Average();
            });

            List <KeyValuePair <IResourceSuppliable, PowerConsumption> > power_draw_items = power_consumption.OrderBy(m => m.Value.Power_draw).ToList();

            power_draw_list_archive = power_draw_items.ToList();
            power_draw_list_archive.Reverse();

            // check priority 1 parts like reactors
            foreach (KeyValuePair <IResourceSuppliable, PowerConsumption> power_kvp in power_draw_items)
            {
                IResourceSuppliable resourceSuppliable = power_kvp.Key;

                if (resourceSuppliable.getPowerPriority() == 1)
                {
                    double power = power_kvp.Value.Power_draw;
                    current_resource_demand       += power;
                    high_priority_resource_demand += power;

                    if (flow_type == FNRESOURCE_FLOWTYPE_EVEN)
                    {
                        power = power * high_priority_demand_supply_ratio;
                    }

                    double power_supplied = Math.Max(Math.Min(currentPowerSupply, power), 0.0);

                    currentPowerSupply      -= power_supplied;
                    total_power_distributed += power_supplied;

                    //notify of supply
                    resourceSuppliable.receiveFNResource(power_supplied, this.resource_name);
                }
            }

            // check priority 2 parts like reactors
            foreach (KeyValuePair <IResourceSuppliable, PowerConsumption> power_kvp in power_draw_items)
            {
                IResourceSuppliable resourceSuppliable = power_kvp.Key;

                if (resourceSuppliable.getPowerPriority() == 2)
                {
                    double power = power_kvp.Value.Power_draw;
                    current_resource_demand += power;

                    if (flow_type == FNRESOURCE_FLOWTYPE_EVEN)
                    {
                        power = power * demand_supply_ratio;
                    }

                    double power_supplied = Math.Max(Math.Min(currentPowerSupply, power), 0.0);

                    currentPowerSupply      -= power_supplied;
                    total_power_distributed += power_supplied;

                    //notify of supply
                    resourceSuppliable.receiveFNResource(power_supplied, this.resource_name);
                }
            }

            // check priority 3 parts like engines and nuclear reactors
            foreach (KeyValuePair <IResourceSuppliable, PowerConsumption> power_kvp in power_draw_items)
            {
                IResourceSuppliable resourceSuppliable = power_kvp.Key;

                if (resourceSuppliable.getPowerPriority() == 3)
                {
                    double power = power_kvp.Value.Power_draw;
                    current_resource_demand += power;

                    if (flow_type == FNRESOURCE_FLOWTYPE_EVEN)
                    {
                        power = power * demand_supply_ratio;
                    }

                    double power_supplied = Math.Max(Math.Min(currentPowerSupply, power), 0.0);

                    currentPowerSupply      -= power_supplied;
                    total_power_distributed += power_supplied;

                    //notify of supply
                    resourceSuppliable.receiveFNResource(power_supplied, this.resource_name);
                }
            }

            // check priority 4 parts like antimatter reactors, engines and transmitters
            foreach (KeyValuePair <IResourceSuppliable, PowerConsumption> power_kvp in power_draw_items)
            {
                IResourceSuppliable resourceSuppliable = power_kvp.Key;

                if (resourceSuppliable.getPowerPriority() == 4)
                {
                    double power = power_kvp.Value.Power_draw;
                    current_resource_demand += power;

                    if (flow_type == FNRESOURCE_FLOWTYPE_EVEN)
                    {
                        power = power * demand_supply_ratio;
                    }

                    double power_supplied = Math.Max(Math.Min(currentPowerSupply, power), 0.0);

                    currentPowerSupply      -= power_supplied;
                    total_power_distributed += power_supplied;

                    //notify of supply
                    resourceSuppliable.receiveFNResource(power_supplied, this.resource_name);
                }
            }

            // check priority 5 parts and higher
            foreach (KeyValuePair <IResourceSuppliable, PowerConsumption> power_kvp in power_draw_items)
            {
                IResourceSuppliable resourceSuppliable = power_kvp.Key;

                if (resourceSuppliable.getPowerPriority() >= 5)
                {
                    double power = power_kvp.Value.Power_draw;
                    current_resource_demand += power;

                    if (flow_type == FNRESOURCE_FLOWTYPE_EVEN)
                    {
                        power = power * demand_supply_ratio;
                    }

                    double power_supplied = Math.Max(Math.Min(currentPowerSupply, power), 0.0);

                    currentPowerSupply      -= power_supplied;
                    total_power_distributed += power_supplied;

                    //notify of supply
                    resourceSuppliable.receiveFNResource(power_supplied, this.resource_name);
                }
            }

            // substract avaialble resource amount to get delta resource change
            currentPowerSupply         -= Math.Max(availableResourceAmount, 0.0);
            internl_power_extract_fixed = -currentPowerSupply * timeWarpFixedDeltaTime;

            pluginSpecificImpl();

            if (internl_power_extract_fixed > 0)
            {
                internl_power_extract_fixed = Math.Min(internl_power_extract_fixed, availableResourceAmount);
            }
            else
            {
                internl_power_extract_fixed = Math.Max(internl_power_extract_fixed, -missingResourceAmount);
            }

            my_part.RequestResource(resourceDefinition.id, internl_power_extract_fixed);

            my_part.GetConnectedResourceTotals(resourceDefinition.id, out availableResourceAmount, out maxResouceAmount);

            if (maxResouceAmount > 0 && !double.IsNaN(maxResouceAmount) && !double.IsNaN(availableResourceAmount))
            {
                resource_bar_ratio = availableResourceAmount / maxResouceAmount;
            }
            else
            {
                resource_bar_ratio = 0.0001;
            }

            //calculate total input and output
            //var total_current_supplied = power_produced.Sum(m => m.Value.currentSupply);
            //var total_current_provided = power_produced.Sum(m => m.Value.currentProvided);
            //var total_power_consumed = power_consumption.Sum(m => m.Value.Power_consume);
            //var total_power_min_supplied = power_produced.Sum(m => m.Value.minimumSupply);

            ////generate wasteheat from used thermal power + thermal store
            //if (!CheatOptions.IgnoreMaxTemperature && total_current_produced > 0 &&
            //    (resourceDefinition.id == thermalpowerResourceDefinition.id || resourceDefinition.id == chargedpowerResourceDefinition.id))
            //{
            //    var min_supplied_fixed = TimeWarp.fixedDeltaTime * total_power_min_supplied;
            //    var used_or_stored_power_fixed = TimeWarp.fixedDeltaTime * Math.Min(total_power_consumed, total_current_produced) + Math.Max(-actual_stored_power, 0);
            //    var wasteheat_produced_fixed = Math.Max(min_supplied_fixed, used_or_stored_power_fixed);

            //    var effective_wasteheat_ratio = Math.Max(wasteheat_produced_fixed / (total_current_produced * TimeWarp.fixedDeltaTime), 1);

            //    ORSResourceManager manager = ORSResourceOvermanager.getResourceOvermanagerForResource(ResourceManager.FNRESOURCE_WASTEHEAT).getManagerForVessel(my_vessel);

            //    foreach (var supplier_key_value in power_produced)
            //    {
            //        if (supplier_key_value.Value.currentSupply > 0)
            //        {
            //            manager.powerSupplyPerSecondWithMax(supplier_key_value.Key, supplier_key_value.Value.currentSupply * effective_wasteheat_ratio, supplier_key_value.Value.maximumSupply * effective_wasteheat_ratio);
            //        }
            //    }
            //}

            currentPowerSupply = 0;
            stable_supply      = 0;

            power_produced.Clear();
            power_consumption.Clear();
        }
Beispiel #56
0
        static async Task Main()
        {
            // for (int x = 0; x < 16; x++)
            // {
            //     for (int y = 0; y < 16; y++)
            //     {
            //         var code = x * 16 + y;
            //         Console.Write($"{Color(code)}{code:000}");
            //     }
            //     Console.WriteLine();
            // }

            // Console.ReadLine();
            Console.OutputEncoding = Encoding.UTF8;
            Console.InputEncoding  = Encoding.UTF8;
            Device = FindDevice();
            try
            {
                await MonitoringMode(true);

                Console.WriteLine($"-- Listening on { Device.Name}, hit 'Enter' to stop...");
                var sb     = new StringBuilder();
                var probes = new Dictionary <CacheEntry, string>();
                var aps    = new List <CacheEntry>();
                Console.Clear();
                while (true)
                {
                    //Console.Clear();
                    sb.Clear();
                    aps.Clear();
                    probes.Clear();

                    foreach (var kvp in BeaconCache.Cache)
                    {
                        foreach (var entry in kvp.Value)
                        {
                            if (DateTime.Now - entry.LastSeen < TimeSpan.FromMinutes(5))
                            {
                                aps.Add(entry);
                            }
                        }
                    }
                    foreach (var kvp in ProbeCache.Cache)
                    {
                        var first = kvp.Value.FirstOrDefault();

                        if (DateTime.Now - first.LastSeen > TimeSpan.FromMinutes(5))
                        {
                            continue;
                        }
                        var ssids = "";
                        foreach (var entry in kvp.Value)
                        {
                            ssids += entry.SSID + ", ";
                        }
                        probes.TryAdd(first, ssids);
                    }

                    sb.AppendLine("############################# PROBES #########################################");
                    sb.AppendLine($"| Last seen | Count | Signal |                         MAC                   |");
                    foreach (var kvp in probes.OrderByDescending(p => p.Key.SignalStrength))
                    {
                        var a = kvp.Key.LastSeen.ToString("HH:mm:ss");
                        var b = $"{kvp.Key.SeenTimes:000}";
                        var c = $"{kvp.Key.SignalStrength:000}";
                        var d = kvp.Key.MAC;
                        var e = kvp.Value;

                        var colorCode = 40;
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromSeconds(5))
                        {
                            colorCode = 41;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromSeconds(15))
                        {
                            colorCode = 42;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromSeconds(30))
                        {
                            colorCode = 43;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromSeconds(45))
                        {
                            colorCode = 44;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromMinutes(1))
                        {
                            colorCode = 62;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromMinutes(2))
                        {
                            colorCode = 56;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromMinutes(3))
                        {
                            colorCode = 54;
                        }
                        if (DateTime.Now - kvp.Key.LastSeen > TimeSpan.FromMinutes(4))
                        {
                            colorCode = 90;
                        }

                        a = Color(colorCode) + a + Color(7);

                        if (kvp.Key.LastSignalStrength - kvp.Key.SignalStrength < -2)
                        {
                            c = Color(40) + c + '+' + Color(7);
                        }
                        else if (kvp.Key.LastSignalStrength - kvp.Key.SignalStrength > 2)
                        {
                            c = Color(1) + c + '-' + Color(7);
                        }
                        else
                        {
                            c = Color(7) + c + ' ' + Color(7);
                        }

                        if (e.EndsWith(", "))
                        {
                            e = e.Remove(e.Length - 2);
                        }

                        sb.AppendLine($"| {a}  |  {b}  |  {c}  | {d} | {e} |");
                    }
                    sb.AppendLine("                                                                              ");
                    sb.AppendLine("############################# BEACONS ########################################");
                    sb.AppendLine($"| Last seen | Count | Signal |     MAC      |               SSID             |");

                    var newest = aps.OrderByDescending(p => p.SignalStrength).Take(25).OrderByDescending(p => p.SignalStrength);

                    foreach (var entry in newest)
                    {
                        var a = entry.LastSeen.ToString("HH:mm:ss");
                        var b = $"{entry.SeenTimes:000}";
                        var c = $"{entry.SignalStrength:000}";
                        var d = entry.MAC;
                        var e = entry.SSID.Trim().Trim(' ').PadRight(30);

                        var colorCode = 40;
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromSeconds(5))
                        {
                            colorCode = 41;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromSeconds(15))
                        {
                            colorCode = 42;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromSeconds(30))
                        {
                            colorCode = 43;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromSeconds(45))
                        {
                            colorCode = 44;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromMinutes(1))
                        {
                            colorCode = 62;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromMinutes(2))
                        {
                            colorCode = 56;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromMinutes(3))
                        {
                            colorCode = 54;
                        }
                        if (DateTime.Now - entry.LastSeen > TimeSpan.FromMinutes(4))
                        {
                            colorCode = 90;
                        }

                        a = Color(colorCode) + a + Color(7);

                        if (entry.LastSignalStrength - entry.SignalStrength < -2)
                        {
                            c = Color(40) + c + '+' + Color(7);
                        }
                        else if (entry.LastSignalStrength - entry.SignalStrength > 2)
                        {
                            c = Color(1) + c + '-' + Color(7);
                        }
                        else
                        {
                            c = Color(7) + c + ' ' + Color(7);
                        }

                        sb.AppendLine($"| {a}  |  {b}  |  {c}  | {d} | {e} |");
                    }
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine(sb);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception e) { Console.WriteLine(e); }
            finally { await MonitoringMode(false); }
        }
Beispiel #57
0
        /*
         * This method sentence-tokenizes all top level comments
         * The best sentences are those where the words in the sentence
         * occur in the most number of subtree items within the current
         * top level comment
         */
        public List <SentenceObj> GetTopSentences(int N)
        {
            List <SentenceObj>          topSentenceObjs      = new List <SentenceObj>();
            List <string>               topSentences         = new List <string>();
            Dictionary <string, double> sentenceScores       = new Dictionary <string, double>();
            Dictionary <string, string> sentenceAuthors      = new Dictionary <string, string>();
            Dictionary <string, string> sentenceCommentTrees = new Dictionary <string, string>();
            Dictionary <string, int>    sentenceIds          = new Dictionary <string, int>();

            foreach (children child in children)
            {
                try
                {
                    Dictionary <string, HashSet <int> > wordIDMapping = GetWordIDMapping(child);
                    string        text          = child.text;
                    List <string> currSentences = SentenceTokenizer.Tokenize(Util.StripTagsCharArray(text));
                    string        bestSentence  = currSentences[0];
                    double        currMax       = double.MinValue;
                    foreach (string sentence in currSentences)
                    {
                        string[] allWords     = GetAllWords(sentence);
                        bool     goodSentence = (allWords.Length > 2) && (stopWords.Where(x => !allWords.Contains(x.ToLower())).Count() > 2);
                        if (goodSentence)
                        {
                            double weightedScore = 0;
                            int    totalIDCount  = 0;
                            foreach (string word in allWords)
                            {
                                if (!stopWords.Contains(word.ToLower()))
                                {
                                    string stemmedWord = Stemmer.GetStem(word);
                                    if (wordIDMapping.ContainsKey(stemmedWord))
                                    {
                                        HashSet <int> idsContainingWord = wordIDMapping[stemmedWord];
                                        totalIDCount  += idsContainingWord.Count;
                                        weightedScore += idsContainingWord.Count * 1.0 / (CommonWords.GetFrequency(word) + 1);
                                    }
                                }
                            }
                            //add some weighting so that longer sentences have more weight
                            weightedScore = weightedScore * (1 - (1 / (Math.Pow(1.25, allWords.Length))));
                            double avgScore = weightedScore / allWords.Length;
                            if (avgScore > currMax)
                            {
                                currMax      = avgScore;
                                bestSentence = sentence;
                            }
                        }
                    }
                    sentenceScores[bestSentence]       = currMax;
                    sentenceAuthors[bestSentence]      = child.author;
                    sentenceCommentTrees[bestSentence] = JsonConvert.SerializeObject(GetCommentTreeString(child));
                    sentenceIds[bestSentence]          = child.id;
                }
                catch (Exception ex)
                {
                }
            }
            topSentences = sentenceScores.OrderByDescending(x => x.Value).Take(N).Where(y => !string.IsNullOrWhiteSpace(y.Key)).Select(x => x.Key).ToList();
            foreach (var sent in topSentences)
            {
                SentenceObj sentenceObj = new SentenceObj()
                {
                    Author = sentenceAuthors[sent], Sentence = sent, SentenceCommentTree = sentenceCommentTrees[sent], Id = sentenceIds[sent], StoryId = this.id
                };
                topSentenceObjs.Add(sentenceObj);
            }
            topSentenceObjs = topSentenceObjs.OrderByDescending(x => GetChildCount(GetNodeById(x.Id))).ToList();
            return(topSentenceObjs);
        }
Beispiel #58
0
        private void skill_SelectedIndexChanged(object sender, EventArgs e)
        {
            var ID = skill.SelectedIndex + 1;
            var q  = db.Competitions.Where(x => x.skillIdFK == ID).ToList();

            total.Text = q.Count().ToString();
            var count = 0;

            #region populating Data grid View
            //Go through each session
            foreach (var item in q)
            {
                //Get the results for that session (for those that are there)
                var q2 = db.Results.Where(x => x.competitionIdFK == item.competitionId).ToList();
                foreach (var i in q2)
                {
                    if (i.q1Marks == 0)
                    {
                        count = 0;
                        continue;
                    }
                    else if (i.q2Marks == 0)
                    {
                        count = 0;
                        continue;
                    }
                    else if (i.q3Marks == 0)
                    {
                        count = 0;
                        continue;
                    }
                    else if (i.q4Marks == 0)
                    {
                        count = 0;
                        continue;
                    }
                    count += 1;
                }

                var q3 = db.Competitors.Where(x => x.skillIdFK == ID).ToList();
                foreach (var i in q3)
                {
                    var q4 = db.Results.Where(x => x.recordsIdFK == i.recordsId).FirstOrDefault();
                    if (q4 == null)
                    {
                        count = 0;
                        continue;
                    }
                }
            }

            completed.Text = count.ToString();

            var qq = db.Competitors.Where(x => x.skillIdFK == ID).ToList();
            dataGridView1.DataSource            = cdt(qq);
            dataGridView1.Columns["MM"].Visible = false;
            #endregion

            #region Getting the Gold, Silver and Bronze People
            //Lists that contain all the G,S and B people!
            Dictionary <string, double> vsG = new Dictionary <string, double>();
            Dictionary <string, double> vsS = new Dictionary <string, double>();
            Dictionary <string, double> vsB = new Dictionary <string, double>();

            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                var total = double.Parse(dr.Cells["Total Marks"].Value.ToString());
                var max   = double.Parse(dr.Cells["MM"].Value.ToString());
                if (total > max * 0.8)
                {
                    vsG.Add(dr.Cells["Competitor"].Value.ToString(), total);
                }
                else if (total > max * 0.75)
                {
                    vsS.Add(dr.Cells["Competitor"].Value.ToString(), total);
                }
                else if (total > max * 0.71)
                {
                    vsB.Add(dr.Cells["Competitor"].Value.ToString(), total);
                }
            }

            if (vsG.Count > 1)
            {
                var vsG2 = vsG.OrderByDescending(x => x.Value).ToList();
                var maxN = vsG2[0].Value;
                vsG.Clear();
                for (int i = 0; i < vsG2.Count(); i++)
                {
                    if (vsG2[i].Value == maxN || vsG2[i].Value >= maxN - 2.0)
                    {
                        vsG.Add(vsG2[i].Key, vsG2[i].Value);
                    }
                    else
                    {
                        vsS.Add(vsG2[i].Key, vsG2[i].Value);
                    }
                }
            }

            if (vsS.Count > 1)
            {
                var vsS2 = vsS.OrderByDescending(x => x.Value).ToList();
                var maxN = vsS2[0].Value;
                vsS.Clear();
                for (int i = 0; i < vsS2.Count(); i++)
                {
                    if (vsS2[i].Value == maxN || vsS2[i].Value >= maxN - 2.0)
                    {
                        vsS.Add(vsS2[i].Key, vsS2[i].Value);
                    }
                    else
                    {
                        vsB.Add(vsS2[i].Key, vsS2[i].Value);
                    }
                }
            }

            if (vsB.Count > 1)
            {
                var vsB2 = vsB.OrderByDescending(x => x.Value).ToList();
                var maxN = vsB2[0].Value;
                vsB.Clear();
                for (int i = 0; i < vsB2.Count(); i++)
                {
                    if (vsB2[i].Value == maxN || vsB2[i].Value >= maxN - 2.0)
                    {
                        vsB.Add(vsB2[i].Key, vsB2[i].Value);
                    }
                }
            }

            dataGridView2.Columns.Clear();
            dataGridView3.Columns.Clear();
            dataGridView4.Columns.Clear();
            dataGridView2.DataSource = cdt1(vsG);
            DataGridViewImageColumn dataGridViewImageColumn = new DataGridViewImageColumn();
            dataGridViewImageColumn.HeaderText = "Image";
            dataGridView2.Columns.Add(dataGridViewImageColumn);
            dataGridView2.Columns[0].Visible = false;

            DataGridViewImageColumn dataGridViewImageColumn1 = new DataGridViewImageColumn();
            dataGridViewImageColumn1.HeaderText = "Image";
            dataGridView3.DataSource            = cdt1(vsS);
            dataGridView3.Columns.Add(dataGridViewImageColumn1);
            dataGridView3.Columns[0].Visible = false;

            DataGridViewImageColumn dataGridViewImageColumn2 = new DataGridViewImageColumn();
            dataGridViewImageColumn2.HeaderText = "Image";
            dataGridView4.DataSource            = cdt1(vsB);
            dataGridView4.Columns.Add(dataGridViewImageColumn2);
            dataGridView4.Columns[0].Visible = false;

            //Testing Code!
            foreach (DataGridViewRow dr in dataGridView2.Rows)
            {
                var key = dr.Cells[0].Value.ToString();
                dr.Cells[1].Style.BackColor = Color.Transparent;
                if (key.Equals("Singapore"))
                {
                    dr.Cells[1].Value = imageList1.Images[6];
                }
                else if (key.Equals("Malaysia"))
                {
                    dr.Cells[1].Value = imageList1.Images[2];
                }
                else if (key.Equals("Indonesia"))
                {
                    dr.Cells[1].Value = imageList1.Images[5];
                }
                else if (key.Equals("Philippines"))
                {
                    dr.Cells[1].Value = imageList1.Images[3];
                }
                else if (key.Equals("Thailand"))
                {
                    dr.Cells[1].Value = imageList1.Images[4];
                }
                else if (key.Equals("Brunei"))
                {
                    dr.Cells[1].Value = imageList1.Images[0];
                }
                else if (key.Equals("Cambodia"))
                {
                    dr.Cells[1].Value = imageList1.Images[1];
                }
            }
            foreach (DataGridViewRow dr in dataGridView3.Rows)
            {
                var key = dr.Cells[0].Value.ToString();
                dr.Cells[1].Style.BackColor = Color.Transparent;
                if (key.Equals("Singapore"))
                {
                    dr.Cells[1].Value = imageList1.Images[6];
                }
                else if (key.Equals("Malaysia"))
                {
                    dr.Cells[1].Value = imageList1.Images[2];
                }
                else if (key.Equals("Indonesia"))
                {
                    dr.Cells[1].Value = imageList1.Images[5];
                }
                else if (key.Equals("Philippines"))
                {
                    dr.Cells[1].Value = imageList1.Images[3];
                }
                else if (key.Equals("Thailand"))
                {
                    dr.Cells[1].Value = imageList1.Images[4];
                }
                else if (key.Equals("Brunei"))
                {
                    dr.Cells[1].Value = imageList1.Images[0];
                }
                else if (key.Equals("Cambodia"))
                {
                    dr.Cells[1].Value = imageList1.Images[1];
                }
            }
            foreach (DataGridViewRow dr in dataGridView4.Rows)
            {
                var key = dr.Cells[0].Value.ToString();
                dr.Cells[1].Style.BackColor = Color.Transparent;
                if (key.Equals("Singapore"))
                {
                    dr.Cells[1].Value = imageList1.Images[6];
                }
                else if (key.Equals("Malaysia"))
                {
                    dr.Cells[1].Value = imageList1.Images[2];
                }
                else if (key.Equals("Indonesia"))
                {
                    dr.Cells[1].Value = imageList1.Images[5];
                }
                else if (key.Equals("Philippines"))
                {
                    dr.Cells[1].Value = imageList1.Images[3];
                }
                else if (key.Equals("Thailand"))
                {
                    dr.Cells[1].Value = imageList1.Images[4];
                }
                else if (key.Equals("Brunei"))
                {
                    dr.Cells[1].Value = imageList1.Images[0];
                }
                else if (key.Equals("Cambodia"))
                {
                    dr.Cells[1].Value = imageList1.Images[1];
                }
            }
            #endregion
        }
Beispiel #59
0
    public static void Main()
    {
        var keyMaterialesNames = new Dictionary <string, string>();

        keyMaterialesNames.Add("shards", "Shadowmourne");
        keyMaterialesNames.Add("fragments", "Valanyr");
        keyMaterialesNames.Add("motes", "Dragonwrath");

        string[] lineArgs = Console.ReadLine().ToLower().Split().ToArray();

        var junkMateriales = new SortedDictionary <string, int>();
        var keyMateriales  = new Dictionary <string, int>();

        keyMateriales.Add("shards", 0);
        keyMateriales.Add("fragments", 0);
        keyMateriales.Add("motes", 0);

        while (true)
        {
            string[] currentMaterials = lineArgs.Where((x, i) => i % 2 == 1).ToArray();
            int[]    quantity         = lineArgs.Where((x, i) => i % 2 == 0).Select(int.Parse).ToArray();

            bool hasObtained = false;

            for (int i = 0; i < currentMaterials.Length; i++)
            {
                string currentMaterial = currentMaterials[i];

                if (keyMaterialesNames.Keys.Contains(currentMaterial))
                {
                    keyMateriales[currentMaterial] += quantity[i];

                    if (keyMateriales.Values.Any(x => x >= 250))
                    {
                        hasObtained = true;
                        break;
                    }
                }
                else
                {
                    if (!junkMateriales.ContainsKey(currentMaterial))
                    {
                        junkMateriales.Add(currentMaterial, 0);
                    }

                    junkMateriales[currentMaterial] += quantity[i];
                }

                if (hasObtained)
                {
                    break;
                }
            }

            if (hasObtained)
            {
                break;
            }

            lineArgs = Console.ReadLine().ToLower().Split().ToArray();
        }

        var obtainedElementName = keyMateriales
                                  .Where(x => x.Value >= 250)
                                  .First()
                                  .Key
                                  .ToString();

        keyMateriales[obtainedElementName] -= 250;

        keyMateriales = keyMateriales
                        .OrderByDescending(x => x.Value)
                        .ThenBy(x => x.Key)
                        .ToDictionary(x => x.Key, x => x.Value);

        Console.WriteLine($"{keyMaterialesNames[obtainedElementName]} obtained!");

        var result = keyMateriales.Concat(junkMateriales).ToDictionary(x => x.Key, x => x.Value);

        foreach (var material in result)
        {
            Console.WriteLine($"{material.Key}: {material.Value}");
        }
    }
Beispiel #60
0
        public Dictionary <string, List <CommentObj> > GetNamedObjects(int N)
        {
            StringBuilder sbAllWords = new StringBuilder();

            foreach (children child in children)
            {
                sbAllWords.Append(child.SubtreeText);
                sbAllWords.Append(" ");
            }
            string[] allWords = GetAllWords(sbAllWords.ToString());
            Dictionary <string, string> stemParentDictionary = GetStemParentDictionary(allWords);
            List <string>         namedObjects = new List <string>();
            children              rootNode     = new children();
            List <HashSet <int> > rootChildIDs = new List <HashSet <int> >();

            foreach (children child in children)
            {
                GetChildIDHashSetList(child);
                HashSet <int> currChildIDs = new HashSet <int>();
                currChildIDs.Add(child.id);
                foreach (var item in child.ChildIDList)
                {
                    currChildIDs.UnionWith(item);
                }
                rootChildIDs.Add(currChildIDs);
            }
            rootNode.ChildIDList = rootChildIDs;
            NodeList             = new List <children>();
            NodeList.Add(rootNode);
            foreach (children child in children)
            {
                PopulateNodeList(child);
            }
            Dictionary <string, HashSet <int> > wordIDMapping = GetWordIDMapping();
            //Dictionary<string, double> WordTreeScore = new Dictionary<string, double>();
            Dictionary <string, List <children> > WordLCAList = new Dictionary <string, List <children> >();

            foreach (var kvp in wordIDMapping)
            {
                List <children> currLCAList = new List <children>();
                int             numLCAs     = 0;
                foreach (children node in NodeList)
                {
                    int numBranchesWithWord = 0;
                    foreach (var childIDBranch in node.ChildIDList)
                    {
                        if (childIDBranch.Intersect(kvp.Value).Count() > 0)
                        {
                            numBranchesWithWord += 1;
                        }
                    }
                    if ((numBranchesWithWord == 1 && node.ChildIDList.Count == 1) || numBranchesWithWord > 1)
                    {
                        currLCAList.Add(node);
                    }
                }
                WordLCAList[stemParentDictionary.ContainsKey(kvp.Key) ? stemParentDictionary[kvp.Key] : kvp.Key] = currLCAList;
            }
            namedObjects = WordLCAList
                           .OrderByDescending(x => x.Value.Count)
                           .Select(x => x.Key)
                           .Where(y => CommonWords.GetFrequency(y) < 1)
                           .Where(a => char.IsUpper(a[0]))
                           .Where(b => b.Length > 1)
                           .Where(z => !(z.EndsWith("n't") || z.EndsWith("'m") || (z.EndsWith("'ll")) || (z.EndsWith("'d")) || z.EndsWith("'ve") || z.EndsWith("'re") || z.EndsWith("'s")))
                           .Take(N)
                           .ToList();
            //namedObjects.Sort();
            Dictionary <string, List <CommentObj> > namedObjectDictionary = new Dictionary <string, List <CommentObj> >();

            foreach (string namedObject in namedObjects)
            {
                List <CommentObj> commentObjsForWord = new List <CommentObj>();
                string            stem        = Stemmer.GetStem(namedObject);
                HashSet <int>     idsWithWord = wordIDMapping[stem];
                foreach (int id in idsWithWord)
                {
                    children   child      = GetNodeById(id);
                    CommentObj commentObj = new CommentObj()
                    {
                        Id = id, Text = child.text
                    };
                    commentObjsForWord.Add(commentObj);
                }
                namedObjectDictionary[namedObject] = commentObjsForWord;
            }
            var ordered = namedObjectDictionary.Keys.OrderByDescending(x => namedObjectDictionary[x].Count).ToList().ToDictionary(x => x, x => namedObjectDictionary[x]);

            return(ordered);
        }