Frequency Distributions

How can I write a program to read a file and out the individual characters in a horizontal bar according to the appearance of each character on the file?
There is some relevant discussion in another recent thread: http://www.cplusplus.com/forum/beginner/279835/

Show us what you've tried so far. If you're having trouble, try to break the assignment into smaller parts. First, just try to read the file and print every character from the file.
http://www.cplusplus.com/doc/tutorial/files/
https://stackoverflow.com/questions/12240010/how-to-read-from-a-text-file-character-by-character-in-c

Displaying a bar graph horizontally (in the terminal, presumably) is a bit more challenging than doing a simple line-by-line vertical print.
I suggest just starting with an array that already has some example frequency distributions in it, and then plot that out by creating a grid with each cell filled in, like a picture with pixels in it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Example program
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

int main()
{
    const int NumLetters = 5; //26
    // a, b, c, ...
    int freqs[NumLetters] = { 9, 4, 5, 0, 6 };
    
    // get the highest frequency to determine how high we need to make the graph
    int height = *std::max_element(freqs, freqs + NumLetters);
    
    std::vector<char> graph(height * NumLetters);

    for (int x = 0; x < NumLetters; x++)
    {
        int offset = height - freqs[x];
        
        for (int y = 0; y < offset; y++)
        {
            graph[y * NumLetters + x] = ' ';   
        }
        for (int y = offset; y < height; y++)
        {
            graph[y * NumLetters + x] = '*';   
        }
    }
    
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < NumLetters; x++)
        {
            std::cout << graph[y * NumLetters + x] << ' ';
        }
        std::cout << '\n';
    }
}

*         
*         
*         
*       * 
*   *   * 
* * *   * 
* * *   * 
* * *   * 
* * *   * 
Last edited on
Thank you Ganado (6032), I really appreciate your time and assistance.

Actually, want the program to read the characters from a text file, and then show the output of each character in these forms below:

The bar would look like this:
The line of 100,000 characters (Example is the number of times A appeared) would look like the one below
032: 500000|********************************************************************************
The line of 250,000 characters (Example is the number of times D appeared) would look like the one below
113: 250000|****************************************

After the 256th row, display a bottom border row of 10 spaces, and then followed by “+” and 50 dashes:
+-------------------------------------------------
Topic archived. No new replies allowed.