ok, so from a design point of view, you have an array of structs, where each struct has an integer "label" and its frequency. When an integer is a label like that, and especially when it goes from 0 to 9, you can usually just simplify it down to using an array's indices as the "labels".
[ 9, 8, 12, ...] for example, would show that 0 occurred nine times, 1 occurred eight times, 2 occurred twelve times, etc. (I didn't change this part)
As for the logic itself, as you said, it's working pretty well, but you want to add the feature of displaying multiple "winners". Some notes:
0. Use [ code ] ... [ /code ] tags (no spaces)
1. Add print statements to actually show what data was generated, and a few mini labels like colons to show that one thing occurred X times
2. Vector is your friend for easily adding an unknown number of items to an array-like container.
3. You can do all your high/low checking during one pass through the items; just need to check conditions carefully
4. Once you assign highest or lowest index 0 of the array, you can iterate through 1...9 (no need to check index 0)
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
#include <iostream>
#include <iomanip>
#include <time.h>
#include <vector>
using namespace std;
struct NUM
{
int n;
int freq = 0;
};
int main()
{
NUM All[10];
int numbers;
srand(time(0));
cout << "Number" << " " << "Frequency" << endl;
cout << "------------------" << endl;
for (int i = 0; i < 10; i++)
{
All[i].n = i;
}
cout << "Generating numbers:\n";
for (int i = 0; i<30; i++)
{
numbers = rand() % 10;
cout << numbers << " ";
All[numbers].freq += 1;
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << " " << All[i].n << ": " <<All[i].freq << " times"<<endl;
}
//--------------------------------------------------------------------------
int highest = All[0].freq;
int lowest = All[0].freq;
vector<int> highs;
vector<int> lows;
for (int i = 1; i < 10; i++)
{
NUM& num = All[i];
if (num.freq > highest)
{
highest = num.freq;
highs.clear();
highs.push_back(num.n);
}
else if (num.freq == highest)
{
highs.push_back(num.n);
}
if (num.freq < lowest)
{
lowest = num.freq;
lows.clear();
lows.push_back(num.n);
}
else if (num.freq == lowest)
{
lows.push_back(num.n);
}
}
cout << "Number(s) with largest frequency of " << highest <<" are ";
for (auto& n : highs)
cout << n << " ";
cout << endl;
cout << "Number(s) with lowest frequency of " << lowest << " are ";
for (auto& n: lows)
cout << n << " ";
cout << endl;
return 0;
}
| |
In action:
https://repl.it/repls/FatalWhitesmokeMetadata