I'll post some code here to get you a bit further, and then make some suggestions on how you could make it better.
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
|
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int x, y, count = 0, max_number, min_number;
int max_count = 0, min_count = 5000, random_number[5000];
srand(time(0));
cout << "Random Number Generation\n";
cout << "************************";
cout << "\n\n Number # of times\n\n";
for(x = 0; x < 5000; x++)
random_number[x] = 1 + rand() % 53;
for(y = 1; y <= 53; y++)
{
for(x = 0; x < 5000; x++)
{
if(random_number[x] == y)
count++;
}
if(count > max_count)
{ // "If the count for this number is greater
max_number = y; // than the previously highest count"
max_count = count;
}
if(count < min_count)
{ // Same as above, but for minimum count
min_number = y;
min_count = count;
}
cout << setw(3) << y << setw(15) << setiosflags(ios::right) << count << endl;
count = 0;
}
cout << "\n\nThe number that came in the least was " << min_number << endl;
cout << "\n\nThe number that came in the most was " << max_number << endl;
system("PAUSE");
}
|
A brief description of the above:
1. Populate the 5000 randoms, like you did.
2. Repeat for each possible random number value:
Go through the randoms and find the number of occurrences, 'count'.
If this 'count' is greater than our previously greatest number of occurrences 'maxCount', then this integer now has our greatest count.
Same as above, but for minimum count.
Housekeeping (reset count to zero, increment y etc).
End loop over possible random numbers.
3. Print the numbers which had maxCount and minCount.
I hope you can see why I initialised maxCount and minCount as shown.
Initialising the min_number to 200 causes a problem on your original line:
if(number_count[min_number] > number_count[y]) {...}
'number_count' can't be indexed over 52, so any min_number greater than that is bad news. I'm surprised you said it "worked correctly"!
Suggestions to make it better:
1. Don't use system("PAUSE") because it's platform-specific (Windows). There are many threads on this site discussing better alternatives.
2. Don't hard-code numbers (even though I left them above). A better way would be to #define constants, or use iterators when going over a collection (worry about that later).
3. Challenge: Try to do it all in one loop. To do this you'd probably need to bring back in the 'number_count' array which I took out.
Hope that helps :).
EDIT: Hmmmm...I should work on reducing the width of my [code] blocks, sorry :).