制作数组直方图的程序

给定一个整数数组,打印数组值的直方图。

null

例如:

Input : 0 11 2 13 5 12 8 11 12 9
Output :                  
13 |           x                   
12 |           x     x        x    
11 |     x     x     x     x  x    
10 |     x     x     x     x  x    
 9 |     x     x     x     x  x  x 
 8 |     x     x     x  x  x  x  x 
 7 |     x     x     x  x  x  x  x 
 6 |     x     x     x  x  x  x  x 
 5 |     x     x  x  x  x  x  x  x 
 4 |     x     x  x  x  x  x  x  x 
 3 |     x     x  x  x  x  x  x  x 
 2 |     x  x  x  x  x  x  x  x  x 
 1 |     x  x  x  x  x  x  x  x  x 
 0 |  x  x  x  x  x  x  x  x  x  x 
---------------------------------------
      0 11  2 13  5 12  8 11 12  9 


Input : 10 9 12 4 5 2 8 5 3 1
Output :                 
12 |        x                      
11 |        x                      
10 |  x     x                      
 9 |  x  x  x                      
 8 |  x  x  x           x          
 7 |  x  x  x           x          
 6 |  x  x  x           x          
 5 |  x  x  x     x     x  x       
 4 |  x  x  x  x  x     x  x       
 3 |  x  x  x  x  x     x  x  x    
 2 |  x  x  x  x  x  x  x  x  x    
 1 |  x  x  x  x  x  x  x  x  x  x 
 0 |  x  x  x  x  x  x  x  x  x  x 
---------------------------------------
     10  9 12  4  5  2  8  5  3  1

其想法是逐行打印给定的直方图。对于每个元素,我们检查它是否大于或等于当前行。如果是,请为该元素添加一个“x”。否则我们就留个空间。

// CPP program to make histogram of an array
#include <bits/stdc++.h>
using namespace std;
void printHistogram( int arr[], int n)
{
int maxEle = *max_element(arr, arr + n);
for ( int i = maxEle; i >= 0; i--) {
cout.width(2);
cout << right << i << " | " ;
for ( int j = 0; j < n; j++) {
// if array of element is greater
// then array it print x
if (arr[j] >= i)
cout << " x " ;
// else print blank spaces
else
cout << "   " ;
}
cout << "" ;
}
// print last line denoted by ----
for ( int i = 0; i < n + 3; i++)
cout << "---" ;
cout << "" ;
cout << "     " ;
for ( int i = 0; i < n; i++) {
cout.width(2); // width for a number
cout << right << arr[i] << " " ;
}
}
// Driver code
int main()
{
int arr[10] = { 10, 9, 12, 4, 5, 2,
8, 5, 3, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
printHistogram(arr, n);
return 0;
}


输出:

                           
12 |        x                      
11 |        x                      
10 |  x     x                      
 9 |  x  x  x                      
 8 |  x  x  x           x          
 7 |  x  x  x           x          
 6 |  x  x  x           x          
 5 |  x  x  x     x     x  x       
 4 |  x  x  x  x  x     x  x       
 3 |  x  x  x  x  x     x  x  x    
 2 |  x  x  x  x  x  x  x  x  x    
 1 |  x  x  x  x  x  x  x  x  x  x 
 0 |  x  x  x  x  x  x  x  x  x  x 
---------------------------------------
     10  9 12  4  5  2  8  5  3  1

本文由 德万舒阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享