問題描述:
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?
解決問題:
這個沒什麼難度。
我們先找到對應關係。
使用數組就夠了。
public class Problem42 {
public static int Len = 0;
public static String[] readNames(){
List<String> names = new ArrayList<String>();
StringBuffer text = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader("f:/words.txt"));
String line ;
while((line=br.readLine())!=null){
text.append(line);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String regex = "\"(.*?)\"";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text.toString());
System.out.println("Number:"+matcher.groupCount());
long total = 0;
int index = 0;
while(matcher.find()){
String name = matcher.group(1);
names.add(name);
if(name.length()>Len)
Len = name.length();
}
System.out.println(names);
String[] result =(String[]) names.toArray(new String[0]);
return result;
}
public static int count_word(String word){
int total = 0;
for(int i=0; i<word.length(); i++){
total+=word.charAt(i)-'A'+1;
}
return total;
}
public static void main(String[] args){
String[] words = readNames();
int sum = 0;
int MAX = Len*26+1;
boolean[] numbers = new boolean[MAX];
Arrays.fill(numbers, false);
int index =1;
int triangle ;
System.out.println("Len:"+numbers.length);
do{
triangle = (index*(index+1))/2;
System.out.println("triangle:"+triangle);
numbers[triangle] = true;
index++;
}while(triangle <MAX);
for(int i=0; i<words.length; i++){
int value = count_word(words[i]);
if(numbers[value]){
sum++;
}
}
System.out.println(sum);
}
}