You are here:

C++/sorting letters in a frequency analysis

Advertisement


Question
I am writing a program which will do a frequency analysis on a wordlist supplied as an argument to main. I accomplish this by initializing a float for each character I wish to count and incrementing that variable whenever that character is encountered. For example:

float acounter; //counts the number of instances of lowercase letter "a"
acounter = 0;
float totalnumberofcharacters; //total number of characters in list
totalnumberofcharacters = 52,345,545;

for(int i = 0; i<word_list.size();i++) //iterates through every word in wordlist
{
  for(int c = 0; c<strlen(wordlist[i]);c++) //iterates through every character in word
  {
     if(word[c]=='a') //if current char is "a"
     {
        acounter++; //add one to the "a" counter
     }
  }
}

std::cout << acounter << " instances of the character "a" (~";
std::cout << (100/ totalnumberofcharacters)*acounter << "%)
";

and the output is, for example:

C:UsersdzhugashviliDesktop reqanal inal>freqanal wordlist3.txt

5000 instances of the character "a" (~.00955%)

C:UsersdzhugashviliDesktop reqanal inal>

However, I am tired of pasting the percentage occurrence of all 95 characters that are analyzed into notepad and manually rearranging them from order of highest occurrence to least occurrence. Is there any way I could have the program sort them for me? In the best-case scenario, I would get a printout in this format:

"etaoinshrdlu....."

just a string of letters from highest occurrence to lowest occurrence. How would I go about this? A 2-D array? Linked lists? Thank you for your help.


Answer
Dear Dzhugashvili:

This can be done a number of ways.

One way is to declare a class of char chr and int count.  Then create an array of 100 such structures. Every time you find a character from the list in a word increment the counter.  Once you have counted all the desired characters in the words, sort the array by the counts, then print the characters in order of counts.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.