49. Text histogram

A histogram is a representation of the distribution of numerical data. Widely known histograms are the color and image histograms that are used in photography and image processing. A text histogram, as described here, is a representation of the frequency of letters in a given text. This problem is partially similar to the previous one, except that the range elements are characters now and we must determine the frequency of them all. To solve this problem you should:

  • Count the appearances of each letter using a map. The key is the letter and the value is its appearance count.
  • When counting, ignore all characters that are not letters. Uppercase and lowercase characters must be treated as identical, as they represent the same letter.
  • Use std::accumulate() to count the total number of appearances of all the letters in the given text.
  • Use std::for_each() or a range-based for loop to go through all the elements of the map and transform the appearance count into a frequency.

The following is a possible implementation of the problem:

std::map<char, double> analyze_text(std::string_view text)
{
std::map<char, double> frequencies;
for (char ch = 'a'; ch <= 'z'; ch++)
frequencies[ch] = 0;

for (auto ch : text)
{
if (isalpha(ch))
frequencies[tolower(ch)]++;
}

auto total = std::accumulate(
std::cbegin(frequencies), std::cend(frequencies),
0ull,
[](auto sum, auto const & kvp) {
return sum + static_cast<unsigned long long>(kvp.second);
});

std::for_each(
std::begin(frequencies), std::end(frequencies),
[total](auto & kvp) {
kvp.second = (100.0 * kvp.second) / total;
});

return frequencies;
}

The following program prints the frequency of the letters from a text on the console:

int main()
{
auto result = analyze_text(R"(Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua.)");

for (auto const & kvp : result)
{
std::cout << kvp.first << " : "
<< std::fixed
<< std::setw(5) << std::setfill(' ')
<< std::setprecision(2) << kvp.second << std::endl;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset