1. 程式人生 > >Poj 2136 Vertical Histogram(列印垂直直方圖)

Poj 2136 Vertical Histogram(列印垂直直方圖)

一、Description

Write a program to read four lines of upper case (i.e., all CAPITAL LETTERS) text input (no more than 72 characters per line) from the input file and print a vertical histogram that shows how many times each letter (but not blanks, digits, or punctuation) appears in the all-upper-case input. Format your output exactly as shown.

Input

* Lines 1..4: Four lines of upper case text, no more than 72 characters per line.

Output

* Lines 1..??: Several lines with asterisks and spaces followed by one line with the upper-case alphabet separated by spaces. Do not print unneeded blanks at the end of any line. Do not print any leading blank lines.

Sample Input

THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.
THIS IS AN EXAMPLE TO TEST FOR YOUR
HISTOGRAM PROGRAM.
HELLO!

Sample Output

                            *
                            *
        *                   *
        *                   *     *   *
        *                   *     *   *
*       *     *             *     *   *
*       *     * *     * *   *     * * *
*       *   * * *     * *   * *   * * * *
*     * * * * * *     * * * * *   * * * *     * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
二、題解

      目標:計算出給定的4行字元序列中每個字母出現的次數用“ * ”表示,並繪製出直方圖。

      問題:1、計算字母出現的次數。 2、列印直方圖

      方法:1、依次讀入每一行到一個字串,將26個字母依次和字串中的字元比較,相符則加1.把結果存放到大小為26的陣列a中。

                  2、找出a陣列中的最大數max,將max迴圈遞減,每次迴圈比較a陣列和max,如果相等則輸出“* ”,否則輸出空格。每次比較完一個max,換行一次。最後輸出A~Z即    可。

      注意:難點在於輸出,剛開始的時候也沒明白。後來一想也挺簡單的。剛開始的時候就用SC.next()讀入四個陣列,結果怎麼都不對,後來發現犯傻了。應該是讀入一行才對,呵呵。這個老師不記得, BufferedReader br=new BufferedReader(new InputStreamReader(System.in));,提醒自己一下。

三、java程式碼

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

  public class Main {
	  static int[] a=new int [27];
	  static int max=-1;
	  public static void count(String s){
		  int i;
		  for(i=0;i<s.length();i++){
			  for(int k=65;k<=90;k++){
				  if((int)s.charAt(i)==k){
					  a[k-64]++;
				  }
				  if(a[k-64]>max)
					  max=a[k-64];
			  }
		 }
	 }
	  public static void main(String[] args) throws IOException  {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       String[] s=new String[4];
       int i,j;
       char c;
       for(i=0;i<4;i++){
    	   s[i]=br.readLine();
    	   count(s[i]);
       }
       for(j=max;j>=1;j--){
			for(i=1;i<=26;i++){
				if(a[i]<j)
					System.out.print("  ");
				else
					System.out.print("* ");
			}
			System.out.println();
	   }	
       for(c='A';c<='Z';c++){
    	   System.out.print(c+" ");
       }
    }  
 }