Algorithm Practice for 1578

Instruens Fabulam
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 598 Accepted: 288

Description

Instruens Fabulam means drawing a chart (or table) in Latin. That's what you will do for this problem.

Input

The input consists of one or more table descriptions, followed by a line whose first character is '*', which signals the end of the file. Each description begins with a header line containing one or more characters that define the number and alignment of columns in the table. Each character in the header line is either '<', '=', or '>', and indicates a left-justified, centered, or right-justified column. Following the header are at least two and at most 21 data lines that contain the entries for each row. Each data line consists of one or more nonempty entries separated by an ampersand ('&'), where the number of entries is equal to the number of columns defined in the header line. The first data line contains entries for the column titles, and the remaining data lines contain entries for the body of the table. Spaces may appear within an entry, but never at the beginning or end of an entry. The characters '<', '=', '>', '&', and '*' will not appear in the input except where indicated above.

Output

For each table description, output the table using the exact format shown in the examples. Note that 
  • The total width of the table will never exceed 79 characters (not counting end-of-line). 
  • Dashes ('-') are used to draw horizontal lines, not underscores ('_'). 'At' signs ('@') appear at each of the four outer corners. Plus signs ('+') appear at intersections within the line separating the title from the body. 
  • The largest entry in a column is always separated from the enclosing bars ('|') by exactly one space. 
  • If a centered entry cannot be exactly centered within a column, the extra space goes on the right of the entry. 

Input and correct output files satisfy all the requirements listed in Notes to Teams, except that the output may contain two or more consecutive spaces. There are no spaces at the beginning or end of lines, and only spaces are used (never tabs). 

Sample Input

<>=>
TITLE&VERSION&OPERATING SYSTEM&PRICE
Slug Farm&2.0&FreeBSD&49.99
Figs of Doom&1.7&Linux&9.98
Smiley Goes to Happy Town&11.0&Windows&129.25
Wheelbarrow Motocross&1.0&BeOS&34.97
>
What is the answer?
42
<>
Tweedledum&Tweedledee
"Knock, knock."&"Who's there?"
"Boo."&"Boo who?"
"Don't cry, it's only me."&(groan)
*

Sample Output

@-----------------------------------------------------------------@
| TITLE                     | VERSION | OPERATING SYSTEM |  PRICE |
|---------------------------+---------+------------------+--------|
| Slug Farm                 |     2.0 |     FreeBSD      |  49.99 |
| Figs of Doom              |     1.7 |      Linux       |   9.98 |
| Smiley Goes to Happy Town |    11.0 |     Windows      | 129.25 |
| Wheelbarrow Motocross     |     1.0 |       BeOS       |  34.97 |
@-----------------------------------------------------------------@
@---------------------@
| What is the answer? |
|---------------------|
|                  42 |
@---------------------@
@---------------------------------------------@
| Tweedledum                 |     Tweedledee |
|----------------------------+----------------|
| "Knock, knock."            | "Who's there?" |
| "Boo."                     |     "Boo who?" |
| "Don't cry, it's only me." |        (groan) |
@---------------------------------------------@
 
Solution:
package id1578;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class InstruensFabulam {
	Queue<Table> chartTableList = null;
	String input = null;
    String inStr = null;
    BufferedReader cin = null;
    Table currentTable = null;
		
	public InstruensFabulam(){
		chartTableList = new LinkedList<Table>();
		cin = new BufferedReader(new InputStreamReader(System.in));
		inStr = "";
	}
	
	private void start() throws IOException{
		  input = cin.readLine();
		  while(input != null && !input.equals("*")){
			  lineParse(input);
			  inStr +=  input + '\n';
			  input = cin.readLine();
		  }
		  currentTable = calculate_colum_width(currentTable);
		  chartTableList.offer(currentTable);
		  while(!chartTableList.isEmpty()){
			  drawThisTable(chartTableList.poll());
		  }
		    
	}
	
	private void lineParse(String strLine){
	   if(isHeadFormat(strLine)){
			if(currentTable != null){
				currentTable = calculate_colum_width(currentTable);
				chartTableList.offer(currentTable);
			}
			currentTable = new Table().putHeadFormat(strLine);
		} else{
			insertToCurrentTable(strLine);
		}
	}
	private void insertToCurrentTable(String strLine){
		if(currentTable.headLine.size() == 0){
			currentTable.headLine = splitAndStore(currentTable.headLine,strLine);
		} else{
			currentTable.body.offer(splitAndStore(new LinkedList<String>(), strLine));
		}
		
	}
	
	private LinkedList<String> splitAndStore(LinkedList<String> que, String str){
		while(str.contains("&")){
			que.offer(str.substring(0,str.indexOf("&")));
			str = str.substring(str.indexOf("&") + 1);
		}
		que.offer(str);
		return que;
	}
	private boolean isHeadFormat(String inStr){
		if(inStr.matches("(<|>|=).*"))
			return true;
		return false;
	}
	
	public static void main(String[] args){
		try {
			new InstruensFabulam().start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void drawThisTable(Table table){
		int totalWidth = 3;
		for(int i = 0; i < table.colWidths.length; i++)
			totalWidth += table.colWidths[i] + 1;
		System.out.print("@");
		for(int i = 0; i < totalWidth - 2; i++)
			System.out.print("-");
		System.out.println("@");
		drawHeadLine(table);
		System.out.print("|");
		for(int i = 0; i < totalWidth - 2; i++)
			System.out.print("-");
		System.out.println("|");
		drawBody(table,totalWidth);
		
	}
	private void drawBody(Table table, int totalWidth){
		LinkedList<String> bodyLine = null;
		while(!table.body.isEmpty()){
			bodyLine = table.body.poll();
			drawBodyHelper(table,bodyLine);
		}
		System.out.print("@");
		for(int i = 0; i < totalWidth - 2; i++)
			System.out.print("-");
		System.out.println("@");
	}
	/* Draw one body line */
	private void drawBodyHelper(Table table,LinkedList<String> bodyLine){
		  for(int i = 0; i < table.colWidths.length; i++){
	    	  System.out.print("|" + " ");
	    	  if(table.headFormat[i] == '<'){
	    		  System.out.print(bodyLine.get(i));
	    		  for(int j = 0; j < table.colWidths[i] - bodyLine.get(i).length(); j++)
	    			  System.out.print(" ");
	    	  } else if(table.headFormat[i] == '>'){
	    		  for(int j = 0; j < table.colWidths[i] - bodyLine.get(i).length(); j++)
	    			  System.out.print(" ");
	    		  System.out.print(bodyLine.get(i));
	    	  }else if(table.headFormat[i] == '='){
	    		  double len = (table.colWidths[i] - bodyLine.get(i).length()) / 2.0;
	    		  int lenInt = (int)len;
	    		  for(int j = 0; j < lenInt; j++)
	    			  System.out.print(" ");
	    		  System.out.print(bodyLine.get(i));
	    		  for(int j = 0; j < lenInt; j++)
	    			  System.out.print(" ");
	    	  }
	      }

			System.out.println("|");
		
	}
	private void drawHeadLine(Table table){
      for(int i = 0; i < table.colWidths.length; i++){
    	  System.out.print("|" + " ");
    	  if(table.headFormat[i] == '<'){
    		  System.out.print(table.headLine.get(i));
    		  try{
    		  for(int j = 0; j < table.colWidths[i] - table.headLine.get(i).length(); j++)
    			  System.out.print(" ");
    		  }catch(Exception e){
    			  System.err.println("colWidths.length is " + table.colWidths.length);
    			  System.err.println("i is " + i);
    			  System.exit(0);
    		  }
    	  } else if(table.headFormat[i] == '>'){
    		  for(int j = 0; j < table.colWidths[i] - table.headLine.get(i).length(); j++)
    			  System.out.print(" ");
    		  System.out.print(table.headLine.get(i));
    	  }else if(table.headFormat[i] == '='){
    		  double len = (table.colWidths[i] - table.headLine.get(i).length()) / 2.0;
    		  int lenInt = (int)len;
    		  for(int j = 0; j < lenInt; j++)
    			  System.out.print(" ");
    		  System.out.print(table.headLine.get(i));
    		  for(int j = 0; j < lenInt; j++)
    			  System.out.print(" ");
    	  }
      }

		System.out.println("|");
	}
	/* Calculate each column's Width*/
	private Table calculate_colum_width(Table table){
		int columnsNum = table.headLine.size();
		table.colWidths = new int[columnsNum];
		int len = Integer.MIN_VALUE;
		for(int i = 0; i < columnsNum; i++)
			table.colWidths[i] = table.headLine.get(i).length() + 2;

		for(int i = 0; i < table.body.size(); i++)
			for(int j = 0; j < table.body.get(i).size(); j++){
				try{
				len = table.body.get(i).get(j).length() + 2;
				}catch(Exception e){
					System.err.println("Err2");
					System.exit(0);
				}
				if(len > table.colWidths[j])
					table.colWidths[j] = len;
			}
		
		
		return table;
	}
	private class Table{
		char[]  headFormat = null;
		LinkedList<String>  headLine = null;
		LinkedList<LinkedList<String>> body = null;
		int[] colWidths = null;
		public Table(){
			headLine = new LinkedList<String>();
			body = new LinkedList<LinkedList<String>>();
		}
		private Table putHeadFormat(String str){
			headFormat = str.toCharArray();
			return this;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值