Hi all,
I've been presented with a small challenge:
1) Make a function that counts the number of each individual character in a string. Report back to the user in the form
So the function would take a string input; i.e. "rabbit" and output the character that occurs the most in said string; i.e. <'b', 2>.
I have coded up a function (to my understanding of Big O notation is that it is Linear O(N)).
public static string GetMostFrequentCharacter(string input)
{
string result = "The String is empty.";
if (IsStringValid(input))
{
int INDEX_CONVERTER = 32;
int[] characterCounts = new int[127 - INDEX_CONVERTER];
char characterToConvert;
// first loop counts the occurrence of each character in the string
for (int i = 0; i < input.Length; i++)
{
characterToConvert = input[i];
characterCounts[(int)characterToConvert - INDEX_CONVERTER]++;
}
int highestCount = 0, arrayPosition = -1;
// second loop finds which character appeared the most, only the last
// highest count to appear in the list will count.
for (int i = 0; i < characterCounts.Length; i++)
{
// check to see if the current index value is higher
// than the previous higher count
if (characterCounts[i] >= highestCount)
{
// get the value at the current index
highestCount = characterCounts[i];
arrayPosition = i;
}
}
if (arrayPosition < 0)
{
result = "There was an error in processing the string.";
}
else
{
// finally, convert the arrayPosition into a suitable char representation
char characterToOutput = (char)(arrayPosition + INDEX_CONVERTER);
// format the output string
result = string.Format("<'{0}', {1}>", characterToOutput, highestCount);
}
}
return result;
}
I'm happy with the way most of it works. My only problem is that, say I have 2 characters that appear an equal number of times. My current method only takes the last highest value, in order of UNICODE value. Say we have the string "foof". The output for said function would be <'o', 2>, it does not present the last letter to appear, only the last in order of UNICODE.
I don't want to create another storage for characters that appear equal number of times (I already have 2 arrays). I have looked on the internet, but the only responses I am finding is if someone knows the character they are looking for, before they use the function; they ask "How many times does 'a' appear?"
Any help or feedback would be greatly appreciated.
Stitchs.