您的位置:首页 > 编程语言 > Java开发

Java 欧拉工程 第二十二篇【 名字得分总和】

2014-08-22 18:00 405 查看
题目是这样的:

文件names.txt(右键另存为)是一个46K大小的文本文件,包含5000多个英文名字。利用这个文件,首先将文件中的名字按照字母排序,然后计算每个名字的字母值,最后将字母值与这个名字在名字列表中的位置相乘,得到这个名字的得分。

例如将名字列表按照字母排序后, COLIN这个名字是列表中的第938个,它的字母值是3 + 15 + 12 + 9 + 14 = 53。所以COLIN这个名字的得分就是938 x53 = 49714.

文件中所有名字的得分总和是多少?

原题:

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting
it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?
解题思路:

第一个难点是文本的读取分割,,我使用的split方法.split("
\" "),就是将文本内容以“ ” “为割将文本分割,得到的是所有的名字和文本里的逗号,但是由于每个名字后面都跟着一个引号,所以在将读取到的名字循环赋入ArrayList时跳开一个,偶数位都是”名字“,奇数位都是”,“。

第二个难点是字母排序,我使用了java中Arraylist来存储每一个名字(String类型),然后 Collections.sort()方法可以使名字按字母排序,计算字母值可以利用字母的ASCII码,转换成数字【1-26】的话-64就行。最后将所有得到的和分别乘以对应的位置,得到结果

871198282,java的代码如下,使用的也是如上的思路:

public class Launcher {

public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
long sum=0L;
ArrayList<String> nameList = new ArrayList<String>();
BufferedReader readTxt=new BufferedReader(new FileReader(new File("X:/p022_names.txt")));//用来存放数字的txt文件
try {
String textLine="";
String  str="";
while((textLine = readTxt.readLine())!=null){//读取文件,循环条件为行不为空
str+=textLine;
}

String[] numList=str.split("\"");//一“”为分割每个数字,分别存入数组intNum中
for(int i=numList.length-1;i>=0;i-=2){
nameList.add(numList[i]);
}
Collections.sort(nameList);
for(int i=0;i<nameList.size();i++){
sum+=letterToNum(nameList.get(i))*(i+1);
}

System.out.println(sum);
readTxt.close();
} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}

// 将大写字母转换成数字
public static long letterToNum(String input) {
long sum=0L;
for (byte b : input.getBytes()) {
sum+=b-64;
}

return sum;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: