using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace MultiThreadTextAnalyzer
{
class Program
{
public static Dictionary<string, int> Transform(List<string> wordList)
{
List<string> transformed = new List<string>();
var sync = new object();
Parallel.ForEach<String>(wordList, wds =>
{
if (wds.Length >= 3)
{
int i = 0;
string temp = "";
while (i < wds.Length - 2)
{
temp = wds.Substring(i, wds.Length - i);
lock (sync)
{
transformed.Add(temp.Substring(0, 3));
}
i++;
}
}
});
transformed.Sort();
Dictionary<string, int> dict = new Dictionary<string, int>();
for (int i = 0; i < transformed.Count; i++)
{
string brand = transformed[i];
int count = 1;
if (dict.ContainsKey(brand))
count = dict[brand] + 1;
dict[brand] = count;
}
return dict;
}
public static void listGen(StreamReader sr, List<string> wordList)
{
int i = 0;
string s = string.Empty;
char c = '\0';
while ((i = sr.Read()) != -1)
{
c = Convert.ToChar(i);
if (Char.IsDigit(c) || Char.IsLetter(c))
{
s = s + c;
}
else
{
if (s.Trim() != string.Empty)
wordList.Add(s);
s = string.Empty;
}
}
}
static void Main(string[] args)
{
Console.WriteLine("TEXT ANALYZER","\n");
string dir = "";
StreamReader file = null;
List<string> words = new List<string>();
try
{
while (true) {
Console.WriteLine("Enter the file path..");
dir = @"" + Console.ReadLine();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
file = new StreamReader(dir);
listGen(file, words);
Dictionary<string, int> rating = Transform(words);
var sortedDict = from entry in rating orderby entry.Value descending select entry;
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Triplet " + sortedDict.ElementAt(i).Key + " is found in this file " + sortedDict.ElementAt(i).Value + " times.");
}
stopwatch.Stop();
Console.WriteLine("Elapsed Time is {0} ms", stopwatch.ElapsedMilliseconds);
}
}
catch (Exception e)
{
if (e is FileNotFoundException)
Console.WriteLine("Error reading from {0}. Message = {1}", dir, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
}
}
}