欧拉计划第42题 统计三角形单词个数
题目:定义三角形数序列中第 n 项:tn=n(n+1)/2
这样得到前十个三角形数是:1, 3, 6, 10, 15, 21, 28, 36, 45, 55, … 把一个单词中每个字母在字母表中的位置值加起来('A’的位置值为 1,'Z’的位置值为 26),
可以将一个单词转换为一个数。
例如:单词 SKY 的值为 19 + 11 + 25 = 55 = t10 (其中’S’的位置值为 19,'K’的位置值为 11, 'Y’的位置值为 25)
如果单词的值是一个三角形数,则称该单词为三角形单词,例如 SKY 就是一个三角形单词。
p042_words.txt 是一个 16K 的文本文件,包含将近两千个常用英语单词。在这个文件中,一
共有多少个三角形词?
答案:162
public static int num(String str){ //一个单词转换为一个数
int sum=0;
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
int a=c-'A'+1;
sum+=a;
}
return sum;
}
public static boolean yesorno(int n){//判断是否为三角形数
int s=n*2;
if(n==1) return true;
int i=1;
for(;i*(i+1)<=s;i++);
if(i*(i-1)==s) return true;
return false;
}
public static void main(String[] args) throws FileNotFoundException {
int nnum=0;//用来记录三角形数的个数
ArrayList<String> nameList = new ArrayList<>();
BufferedReader br=new BufferedReader(new FileReader(new File("E:\\project\\p042_words.txt")));
//用来存放数字的txt文件
try {
String textLine="";
String str="";
while((textLine = br.readLine())!=null){//读取文件,循环条件为行不为空
str+=textLine;
}
String[] numList=str.split("\"");
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++){
int n=num(nameList.get(i));
if(yesorno(n))
nnum++;
}
System.out.println(nnum);
br.close();
} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}