Advertisement
yarik2803

Strings

Mar 22nd, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ex1
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             string text = Console.ReadLine();
  12.             List<string> words = text.Split(new char[] {',', ' ', '.', '!', '?', '-'}).ToList();
  13.  
  14.             // The laziest solution -> prints how many times every word exists in the given input
  15.             //while (words.Count != 0)
  16.             //{
  17.             //    string word = words[0];
  18.             //    Console.WriteLine(word + "--> " + words.Count(x => x == word));
  19.             //    words.RemoveAll(x => x == word);
  20.             //}
  21.  
  22.  
  23.             // This solution prints the most common word in the given input
  24.             int maxCounter = 0;
  25.             string maxWord = string.Empty;
  26.             int currentCounter = 1;
  27.             for (int i = 0; i < words.Count; i++)
  28.             {
  29.                 if (HasBeenEarlier(words, i)) // Just optimization
  30.                 {
  31.                     continue;
  32.                 }
  33.                 if (maxCounter >= words.Count - i) // Another optimization
  34.                 {
  35.                     break;
  36.                 }
  37.  
  38.                 for (int j = i + 1; j < words.Count; j++)
  39.                 {
  40.  
  41.                     if (words[i] == words[j])
  42.                     {
  43.                         currentCounter += 1;
  44.                     }
  45.                 }
  46.  
  47.                 if (currentCounter > maxCounter)
  48.                 {
  49.                     maxCounter = currentCounter;
  50.                     maxWord = words[i];
  51.                 }
  52.                 currentCounter = 1;
  53.             }
  54.             Console.WriteLine("The moast common word is: " + maxWord + " --> " + maxCounter);
  55.            
  56.         }
  57.  
  58.         static bool HasBeenEarlier(List<string> words, int border)
  59.         {
  60.             for (int i = 0; i < border; i++)
  61.             {
  62.                 if (words[i] == words[border])
  63.                 {
  64.                     return true;
  65.                 }
  66.             }
  67.             return false;
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement