Lab 5. Array

Task 1. Counting frequencies of integers read from a file

/*
  Author: Alexey Nikolaev
  Description: Lab 5. Task 1. Counting frequencies of integers
    Usage: 
      ./a.out < file
*/

#include <iostream>

using namespace std;

const int N = 1000;

int main () {
  
  int n;
  int max = 0;
  int count[N] = {0};

  while (cin >> n) {
    if (n > max) {
      max = n;
    }
    count[n]++;
  }

  cout << "i\tcount" << endl;
  cout << "-------------" << endl;
  for(int i = 0; i <= max; i++) {
    cout << i << '\t' << count[i] << endl;
  }
}

Task 2. Histogram

/*
  Author: Alexey Nikolaev
  Description: Lab 5. Task 2. Histogram
    Usage: 
      ./a.out < file
*/

#include <iostream>

using namespace std;

const int N = 1000;

// print a bar of length n
void bar(int n);

int main () {
  
  int n;
  int max = 0;
  int count[N] = {0};

  while (cin >> n) {
    if (n > max) {
      max = n;
    }
    count[n]++;
  }

  cout << "i\tcount" << endl;
  cout << "-------------" << endl;
  for(int i = 0; i <= max; i++) {
    cout << i << '\t';
    bar(count[i]);
    cout << ' ' << count[i] << endl;
  }
}

void bar(int n) {
  for(int i = 0; i < n; i++)
    cout << '|';
}

Task 3. Histogram printed in the descending order from the most frequent to the least frequent

/*
  Author: Alexey Nikolaev
  Description: Lab 5. Task 2. Sorted histogram
    Usage: 
      ./a.out < file
*/

#include <iostream>
#include <cassert>

using namespace std;

const int N = 1000;

// print a bar of length n
void bar(int n);

int main () {
  
  int n;
  int max = 0;
  int count[N] = {0};

  while (cin >> n) {
    if (n > max) {
      max = n;
    }
    count[n]++;
  }

  cout << "i\tcount" << endl;
  cout << "-------------" << endl;

  bool printed[N] = {0};
  for(int i = 0; i <= max; i++) {
    // choose the best 
    // initialize with an invalid value
    int index_best = -1;
    
    for(int j = 0; j <= max; j++) {
      if (printed[j] == false && (index_best < 0 || count[j] > count[index_best])) 
        index_best = j;
    }
    
    // assert that index_best is a valid value
    assert(index_best >= 0 && index_best <= max);

    printed[index_best] = true;

    cout << index_best << '\t';
    bar(count[index_best]);
    cout << ' ' << count[index_best] << endl;
  }
}

void bar(int n) {
  for(int i = 0; i < n; i++)
    cout << '|';
}