一道長度轉換的題

前些日子報了某比賽,有個簡單的測試。 php

length
題目介紹

您要作的是一個長度單位轉化和計算工具,可以把不一樣的長度單位轉換爲標準長度(米),而且能夠在不一樣單位之間進行加減運算。

輸入文件

輸入文件input.txt的內容可分爲兩部分:

不一樣單位和標準長度米的轉換規則, 好比
1 mile = 1609.344 meters, 表明1英里等於1609.344米;

轉換前或者計算前的單位,好比 1.2 miles // 一個長度 1.2 miles + 1 fath - 0.2 meters // 單位可能不一樣的長度之間的加減運算
您要作的

咱們指望您編寫一個應用程序,能夠讀取輸入文件,瞭解不一樣單位與米之間的轉換規則後,把以不一樣單位表示的長度都轉換爲標準單位米;同時計算不一樣單位長度的加減表達式,獲得以米爲單位的結果。

作題要求:

請必定Fork本倉庫再作題目

使用的編程語言不限

輸出結果爲文件"output.txt",其格式見下面說明

源代碼和結果文件"output.txt"上傳到您的GitHub代碼庫中

結果文件「output.txt」必定要放到代碼庫的根目錄下

輸出文件格式

該文件的格式共有12行,並嚴格遵照如下規則:

第1行是您的郵箱,好比 myName@gmail.com  第2行是空行

第3行至第12行,每行顯示1個計算結果,好比1931.21 m

計算結果要求精確到小數點後兩位

計算結果均以字母m結尾,請注意數字和字母m之間有一個空格。

input.txt java

1 mile = 1609.344 m
1 yard = 0.9144 m
1 inch = 0.00254 m
1 foot = 0.03048 m
1 fath = 1.8288 m
1 furlong = 201.17 m

1.2 miles
0.15 yard
32.7 inches
127.93 feet
22 faths
0.032 furlong
1 furlong + 2.5 feet
0.9 miles - 18 inches
1 fath - 1 foot + 12.5 inches
3.02 miles + 17.5 yards - 0 fath

 

 

 

題目很是簡單,只是看到你們的方式,仍是眼前一亮。 git

先說我本身作的: github

package com.github.alaahong;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.alaahong.FormatSeparator.FormatException;

public class Format {

	/**
	 * @author Ian Zhang
	 * @param args
	 * @throws FormatException
	 * @throws NumberFormatException
	 *             please use JDK1.7+
	 */
	public static void main(String[] args) throws NumberFormatException,
			FormatException {
		try {
			// read file content from file
			List<String[]> tempList = new ArrayList<String[]>();
			List<Double> doubleList = new ArrayList<Double>();
			Map<String, Double> tempMap = new HashMap<String, Double>();
			FileReader reader = new FileReader(System.getProperty("user.dir")
					+ File.separator + "input.txt");
			BufferedReader br = new BufferedReader(reader);
			String str = null;
			int counter = 0;
			while ((str = br.readLine()) != null) {
				tempList.add(str.split(" "));
			}
			FormatSeparator fs = new FormatSeparator();
			for (String[] s : tempList) {
				if (counter < 6) {
					tempMap.put(s[1], Double.parseDouble(s[3]));
					counter++;
				} else if (counter++ > 6 && counter < 18) {
					Double tempDouble = 0d;
					for (int i = 0; i < s.length; i++) {
						if (i == 0) {
	tempDouble += Double.parseDouble(s[i])* tempMap.get(fs.formatSeparator(s[i + 1]));
						} else if (((i - 2) % 3) == 0) {
							if (s[i].equals("+")) {
	tempDouble += Double.parseDouble(s[i + 1])* tempMap.get(fs.formatSeparator(s[i + 2]));
							} else if (s[i].equals("-")) {
	tempDouble -= Double.parseDouble(s[i + 1])* tempMap.get(fs.formatSeparator(s[i + 2]));
							}
						}
					}
					doubleList.add(tempDouble);
				}
			}
			br.close();
			reader.close();

			// write string to file
			FileWriter writer = new FileWriter(System.getProperty("user.dir")
					+ File.separator + "output.txt");
			BufferedWriter bw = new BufferedWriter(writer);
			DecimalFormat df = new DecimalFormat("0.00");
			String crlf = System.getProperty("line.separator");
			bw.write("e-mail address");
			bw.write(crlf + "");
			for (Double d : doubleList) {
				bw.write(crlf + df.format(d) + " m");
			}
			bw.close();
			writer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
package com.github.alaahong;

public class FormatSeparator {
	public String formatSeparator(String measure) throws FormatException {
		switch (measure) {
		case "mile":
			measure = "mile";
			break;
		case "miles":
			measure = "mile";
			break;
		case "yard":
			measure = "yard";
			break;
		case "yards":
			measure = "yard";
			break;
		case "inch":
			measure = "inch";
			break;
		case "inches":
			measure = "inch";
			break;
		case "foot":
			measure = "foot";
			break;
		case "feet":
			measure = "foot";
			break;
		case "fath":
			measure = "fath";
			break;
		case "faths":
			measure = "fath";
			break;
		case "furlong":
			measure = "furlong";
			break;
		case "furlongs":
			measure = "furlong";
			break;
		case "m":
			measure = "m";
			break;
		case "meters":
			measure = "m";
			break;
		default:
			throw new FormatException(measure);
		}
		return measure;

	}

	public class FormatException extends Exception {
		/**
		 * define my exception
		 */
		private static final long serialVersionUID = 1L;

		public FormatException() {
			super();
			System.out.println("Formating Error!");
		}

		public FormatException(String msg) {
			super(msg);
			System.out.println("Formating Error!");
		}
	}
}

 

錢總最近寫腳本比較多,他用的ruby shell

class Length
  def initialize
    @map = Hash.new
    @result = Array.new(10,0)
    @count = 0
  end
  
  def map
    @map
  end
  
  def setFile(fn = "input.txt")
      @file = fn
  end
  
  def readFile()
      File.open(@file,"r") do |file|
          while line=file.gets
              if match = /\s*\d+\s*(\w+)\s*=\s*(\d+.\d*)\s*m\s*/.match(line)       
                  @map[match[1]] = match[2].to_f
              elsif line.lstrip!=""
                calculate(toSingle(line),@count)
                @count += 1 
              end
          end
      end
  end
  
  #把複數變成單數
  def toSingle(str)
    str = str.gsub(/miles/,"mile")    
    str = str.gsub(/inches/,"inch") 
    str = str.gsub(/feet/,"foot") 
    str = str.gsub(/yards/,"yard")
    str = str.gsub(/faths/,"fath")
  end
  
  #轉化成米爲單位
  def transfer(str)
    if  match = /\s*(\d+(.\d+){0,1})\s*(\w+)/.match(str)
      return match[1].to_f * @map[match[3]]
    end
  end
  
  #計算表達式
  def calculate(str,n)
    if  match = /(\s*\d+(.\d+){0,1}\s*\w+)((\s*([+-])\s*\d+(.\d+){0,1}\s*\w+)*)/.match(str)
      @result[n] += transfer(match[1])
    end
    if match[3].to_s.lstrip != ""
      substr = match[3]
      while subMatch = /(([+-])\s*\d+(.\d+){0,1}\s*\w+)(\s*[+-][\d\w\s.]+)*/.match(substr)
        if subMatch[2] == "+"
          @result[n] += transfer(subMatch[1])
        elsif subMatch[2] == "-"
          @result[n] -= transfer(subMatch[1])
        end
        if subMatch[4].to_s.lstrip != ""
            substr = subMatch[4]
        else
            break
        end
      end
      
    end
  end
  
  #保留兩位小數
  def doFormat
    10.times do |i|
      @result[i] = format("%.2f",@result[i])
    end
  end
  
  #寫入文件
  def appendFile
    f = File.new("output.txt","w") #覆蓋---w 追加---a
      f.puts("e-mail address")
      f.puts
      10.times do |i|
          f.puts(@result[i].to_s + " m" )
      end
    f.close
  end
  
end


f = Length.new
f.setFile
f.readFile
f.doFormat
f.appendFile

 

原本覺得鑫磊會按比賽的習慣去寫C++的,沒想到用php了 編程

<?php
   $file = file_get_contents('input.txt');
   $out = explode("\n", $file);
   $out_val = array();
   $file = fopen("output.txt","a");
   fwrite($file,"e-mail address\r\n");
   fwrite($file,"\r\n");
   
   foreach($out as $key => $value)
   {
		$val = explode(' ', $value);
		if(count($val) == 1) continue;

		if(in_array('=', $val))
		{
			if($val[1] == 'mile') 
			{
			   $out_val['miles'] = $val[3];
			   $out_val['mile'] = $val[3];
			}
			else if($val[1] == 'yard')
			{
			   $out_val['yard'] = $val[3];
			   $out_val['yards'] = $val[3];
			}
		    else if($val[1] == 'inch')
			{
		       $out_val['inch'] = $val[3];
		       $out_val['inches'] = $val[3];
			}
			else if($val[1] == 'foot')
			{
			   $out_val['foot'] = $val[3];
			   $out_val['feet'] = $val[3];
			}
			else if($val[1] == 'fath')
			{
			    $out_val['fath'] = $val[3];
			    $out_val['faths'] = $val[3];
			}
			else if($val[1] == 'furlong')
			{
				$out_val['furlong'] = $val[3];
			}
		}
		else if(in_array('+', $val) || in_array('-', $val))
		{
			$j = trim($val[1]);
			$sum = $out_val[$j]*$val[0];		
			for($i = 1; $i <= (count($val)-2)/3; $i++)
			{
			    $j = $val[$i*3+1];
				$j = trim($j);
				$ret = $out_val[$j]*$val[$i*3];
				if($val[$i*3-1] == '+') 
				{
				   $sum = $sum+$ret;
				}
				else 
				{
				   $sum = $sum-$ret;
				}
			}
			$sum = sprintf("%.2f",$sum);
			fwrite($file,"$sum m\r\n");

		}
		else 
		{
			$j = trim($val[1]);
		    $sum = $out_val[$j]*$val[0];
			$sum = sprintf("%.2f",$sum);

			fwrite($file,"$sum m\r\n");	
		}
	}
	fclose($file);

?>

 

幾我的不見,你們風格變化很多...  ruby

相關文章
相關標籤/搜索