I have a string array containing the names of 10 countries (max length of 100). I have another array containing the corresponding total amount that country won. The two arrays look like this:
char countryNames[10][100] = {"Japan", "USA", "China", "ROC", "UK", "Australia",
"Kosova", "Italy", "France", "Canada"}
int totalMedals[10] = {13, 14, 18, 12, 7, 6, 2, 9, 5, 4}
So Japan won 13 medals, USA won 14 medals, ... etc. I'm having trouble finding a way to output these statistics in a vertical histogram using *'s. This is the output I am looking for:
I can't find a solution to this that isn't extremely hard coded. There is no specific spacing but I want it to look mostly like the example. Can anyone help me do this?
CodePudding user response:
You output a vertical histogram by outputting one line after the other.
I.e. you have to drop the whole "vertical" idea and force everything into lines, by a generous amount of foresight.
Basically:
Step 1: Find pad
, the length of the longest name.
Step 2: Find total
, the total number of entries.
Step 3: Create a newline-and-zero-terminated character sequence of pad * total
blanks.
Step 4: Find index
, the index of the highest number.
Step 5: Change the blank at position index * pad
to '*'
.
Step 6: Find next
, the index of the next highest number.
Step 7: Output the character sequence totalMedals[index]-totalMedals[next]
times.
Step 8: Copy the value of next
into index
.
Step 9: Repeat from step 5 until you are done, using 0 as an additional last number.
Then you only need to output the names with padding according to preference.
This is simplified by the assumption of unique numbers of medals, i.e. no two have the same number - as in your input data. (Though I suspect it might actually also work for non-unique numbers.)
CodePudding user response:
int max_medals = 0;
int total_countries = totalMedals.length; //this is 10 here
// here we are finding how many max medals have been won, this will
// allow us to find the height of the matrix
for (int i=0; i<total_countries; i )
max_medals = max(totalMedals[i], max_mexdals);
// create the matrix representing histogram
char matrix[total_countries][max_medals];
// traversing left to right, bottom to up, if that country
// has 'j 1' number of medals, fill the matrix else let it be blank
for(int j=0; j<max_medals; j )
for(int i =0; i<total_countries; i )
if(totalMedals[i] <= j 1)
matrix[i][j] = '*'
else
matrix[i][j] = ' '
Confirm the syntax and edge cases once, hope this helps!