Advertisement
simeon3000

Array Histogram KVP

Sep 21st, 2017
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1.             string[] inputWords = Console.ReadLine().Split(' ').ToArray();
  2.             int inputWordsCount = inputWords.Length;
  3.             List<KeyValuePair<string, int>> wordsAndCounts =
  4.                                                 new List<KeyValuePair<string, int>>();
  5.             foreach (string word in inputWords)
  6.             {
  7.                 if (!wordsAndCounts.Exists(kvp => kvp.Key == word))
  8.                 {
  9.                     wordsAndCounts.Add(new KeyValuePair<string, int>(word, 1));
  10.                 }
  11.                 else
  12.                 {
  13.                     for (int i = 0; i < wordsAndCounts.Count; i++)
  14.                     {
  15.                         if (wordsAndCounts[i].Key == word)
  16.                         {
  17.                             int currCount = wordsAndCounts[i].Value;
  18.                             wordsAndCounts.RemoveAt(i);
  19.                             wordsAndCounts.Insert(i, new KeyValuePair<string, int>
  20.                                                                 (word, currCount + 1));
  21.                             break;
  22.                         }
  23.                     }
  24.                 }
  25.             }
  26.            
  27.             var sortedWordsByCounts = wordsAndCounts.OrderByDescending(kvp => kvp.Value);
  28.            
  29.             foreach (var pair in sortedWordsByCounts)
  30.             {
  31.                 double percentage = (double)pair.Value / inputWordsCount * 100;
  32.                 Console.WriteLine($"{pair.Key} -> {pair.Value} times ({percentage:F2}%)");
  33.             }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement