Problem 42

问题描述:

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?

解决问题:

这个没什么难度。

我们先找到对应关系。

使用数组就够了。

扫描二维码关注公众号,回复: 1345162 查看本文章
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);
	}
}

猜你喜欢

转载自to-zoe-yang.iteye.com/blog/1155568
42
42.