Just saw Andy's second response -- yep, this is the second strat I was going to mention, though the it should be done with just one O(n) loop without nesting:
1. Grab 101 indices of space to track frequencies of all numbers in range 0 to 100, inclusive
2. Initialize all these to 0
3.
At the moment of input, increment values in the indices as each input number is read
Also shown here is another way to do a loop X times, by decrementing the total:
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
|
#include <iostream>
using namespace std;
int main()
{
const int MAX = 100;
int total;
cout << "Please input the total number of integers (1 to 20): ";
cin >> total;
if (total <= 0)
{
cout << "Error: total '"<< total <<"' should be greater than 0" << endl;
return -1;
}
cout << "Please input " << total << " space-separated integers (0 to "
<< MAX << "): ";
// Using index to store frequency for all possible values in range
int a[MAX+1]{};
int n;
while (total--)
{
cin >> n;
a[n] += 1;
}
// Analysis is now just a matter of outputting non-zero values
cout << endl << "Frequencies:" << endl;
for (int i=0; i<=MAX; ++i)
{
if (a[i])
cout << " " << i << ": " << a[i] << endl;
}
return 0;
}
|
A careful observer might wonder, "Hmm... is there a way to avoid using more space than I need, and avoid iterating through 80+ indices of zeroes before spotting my input?". Since this latest strat's loop actually iterates 101 times, it could ironically be slower than the previous strat's nested (total*total), if total is 10 or less.
And so, we come to one of my great loves: maps. This is not an array solution, but is pretty much the go-to strat for calculating frequencies. The key is the token (an integer in this case), and the value is an integer that increases with each sighting of that token. (Aside: std::map is ordered by default, but if you need that extra performance boost, you could use std::unordered_map). In C++, the key-value pairs are stored in "first" and "second" variables, respectively.
A bonus over strat #2 is that the user is no longer limited to range [0, 100] because we don't explicitly need to spend time acquiring this space.
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
|
#include <iostream>
#include <map>
using namespace std;
int main()
{
int total;
cout << "Please input the total number of integers (1 to 20): ";
cin >> total;
if (total <= 0)
{
cout << "Error: total '"<< total <<"' should be greater than 0" << endl;
return -1;
}
cout << "Please input " << total << " space-separated integers: ";
map<int,int> freq;
int n;
while (total--)
{
cin >> n;
freq[n] += 1;
}
cout << endl << "Frequencies:" << endl;
for (auto& kv : freq)
cout << " " << kv.first << ": " << kv.second << '\n';
return 0;
}
|