I had 15 minutes to code the following question:
Given a file name return the char which appears maximal number of times.
please do not take into account the unit test. Please look at the final foreach loop, I could have also used a for loop, I have doubts what is the best way to implement finding a max value and get the key from the dictionary.
Also please comment about code style. Thanks
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace JobInterviewTests
{
[TestClass]
public class GetMostRepeatedCharQuestion
{
[TestMethod]
public void TestForAasMax()
{
char result = GetMaxCharHelper.GetMaxReaptedCharFromFile("MaxA.txt");
Assert.AreEqual('A', result);
}
}
public class GetMaxCharHelper
{
public static char GetMaxReaptedCharFromFile(string fileName)
{
Dictionary<char, int> charToCount = new Dictionary<char, int>();
using (var streamReader = new StreamReader(fileName))
{
string line = streamReader.ReadLine();
while (line != null)
{
char[] charArray = line.ToCharArray();
foreach (var currentChar in charArray)
{
if (charToCount.ContainsKey(currentChar))
{
charToCount[currentChar]++;
}
else
{
charToCount.Add(currentChar, 1);
}
}
//don't forget to get next line when reading from a file
line = streamReader.ReadLine();
}
int maxCount = 0;
char maxChar = '\0';
foreach (var current in charToCount)
{
if (current.Value > maxCount)
{
maxCount = current.Value;
maxChar = current.Key;
}
}
return maxChar;
}
}
}
}