路徑:Tournament \ 1-16 \ 1 - Inv 2001 R1 \ HowEasy
分數:250
題目
程式介面
Class Name: HowEasy Method Name: pointVal Parameters: String Returns: int
說明
TopCoder的題目依難度有三種分數,現在想要撰寫一個程式,能夠依據題目的描述的平均字長(Average Word Length)來決定分數:
- 平均字長小於等於3為250分。
- 平均字長4或5為500分。
- 平均字長大於等於6為1000分。
定義
- Token:句子中的字元集以空白切開為。
- Word:Token由[a-zA-Z]組成,可能會有點結尾(.),且至少一個字元。
- Word Length:一個Word的字元數。
- Average Word Length:所有Word的Word Length總和除以Word數,其中點不算字數,當Word數為0時Average Word Length為0。
系統保證輸入
- 1 - 50個字元,包含字母、數字、空白和點。
範例
輸入:"This is a problem statement" 輸出:500 註:Average Word Length = 23 / 5 = 4 輸入:"523hi." 輸出:250 註:Average Word Length = 0 輸入:"Implement a class H5 which contains some method." 輸出:500 註:Average Word Length = 38/ 7 = 5 輸入:" no9 . wor7ds he8re. hj.." 輸出:250 註:Average Word Length = 0
解法
這是單純的文字處理題型,可以直覺得從切割Token後,逐一判斷Token是否為字,對相對應的機總計算,在細節上要注意:
- 結尾的點判斷與不列入字數計算。
- 字數為0的處理(避免除以0)。
- 平均字長是用字數除,而非Token數除。
語法
採用較易理解的寫法,效能並非最好
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace HowEasy { class HowEasy { private static Regex wordReg = new Regex(@"^[A-Za-z]+(\.)?$", RegexOptions.Compiled); public int pointVal(string param0) { int wordCount = 0, length = 0; string[] tokens = param0.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string token in tokens) { Match match = wordReg.Match(token); if (match.Success) { ++wordCount; length += token.Length; // 點結尾時, 扣除1的字數 if (match.Groups[1].Success) --length; } } int average = wordCount == 0 ? 0 : length / wordCount; if (average <= 3) return 250; if (average >= 6) return 1000; return 500; } } }
下載