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, a 16K text file containing nearly two-thousand common English words, how many are triangle words?
問 42 「符号化三角数」
三角数のn項は \( t_{n} = n(n+1)/2 \) で与えられる. 最初の10項は
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
である.
単語中のアルファベットを数値に変換した後に和をとる. この和を「単語の値」と呼ぶことにする. 例えば SKY は 19 + 11 + 25 = 55 = \( t_{10} \) である. 単語の値が三角数であるとき, その単語を三角語と呼ぶ.
16Kのテキストファイル words.txt 中に約2000語の英単語が記されている. 三角語はいくつあるか?
Because the original word list is very long, this example has only a part of it.
fn is_triangle_number(x: u32) -> bool { let expr = 8 * x + 1; let side = (expr as f64).sqrt() as u32; side * side == expr } fn word_value(w: &str) -> u32 { w.chars().map(|c| c as u32 - 'A' as u32 + 1).sum::<u32>() } fn main() { let count = WORDS .iter() .map(|&w| word_value(w)) .filter(|&v| is_triangle_number(v)) .count(); println!("{:?}", count); assert_eq!(count, 5); } const WORDS: &[&str] = &[ "A", "ABILITY", "ABLE", "ABOUT", "ABOVE", "ABSENCE", "ABSOLUTELY", "ACADEMIC", "ACCEPT", "ACCESS", "ACCIDENT", "ACCOMPANY", "ACCORDING", "ACCOUNT", "ACHIEVE", "ACHIEVEMENT", "ACID" ];