Apart from everything that's been said already, you could improve the code by making it more const
-correct. This may be different for C, but in C++, you almost certainly want to have
char mostFrequent(char const* bytes, int length) {
This will allow your function to be called with string literals without invoking a deprecated conversion (char const*
to char*
).
In addition to this, if you know you're going to be working with strings, you might as well have it use null-termination, as you can expect it to be present anyway. It also allows for more elegant (in my opinion) expression of the intent, especially if you use 'a'
instead of 97
.
char mostFrequent(char const* bytes) {
// Leaving this array as it is to change the rest of the code less.
int holder[26] = {};
for (char const* p = bytes; *p; ++p) {
if (*p >= 'a' && *p <= 'z') // omit this check if you're sure it's true
++holder[*p - 'a'];
}
// With that out of the way, you can also
// get rid of some of the 97s here:
int indexOfMax = 0;
for (int i = 1; i < 26; i++) {
if (holder[i] > holder[indexOfMax])
indexOfMax = i;
}
return 'a' + indexOfMax;
}
As has been said, you should probably pull the last loop into a different function; I'd say you should pull the array into another function, too. You could use the standard library if you're using C++, but this is also a perfectly fine piece of C code.
Something that you haven't shown us are the tests you're running on this code. Assuming you've factored some things out, so that your function looks like this:
char mostFrequent(char const* bytes) {
int holder[26] = {};
populateFromString(holder, 26, bytes);
return 'a' + findIndexOfMaxIn(holder, 26);
}
Now you can easily test each of the functions separately. For example,
void testPopulationWithAlphabet() {
char holder[26] = {};
populateFromString(holder, 26, "abcdefghijklmnopqrstuvwxyz");
for (int i = 0; i < 26; ++i)
assert(holder[i] == 1);
}
void testFindIndexOfMaxWithNoDuplicates() {
int arr[5] = {0, 1, 6, 2, 3};
assert(findIndexOfMaxIn(arr, 5) == 6);
}
void testFindMostFrequentCharacterWithNoTies() {
assert(mostFrequent("helloworld") == 'l');
}
You probably want some kind of testing framework to run these tests in, although just using assert.h
(or cassert
in C++) may also be enough. Your function may be fairly short, but 12 lines is non-trivial, and you'll spend less time debugging if you split your code up and write tests for it.