Project Euler
Problem 42(Coded triangle numbers)
(이경수)
2019. 7. 24. 15:31
Problem 42(Coded triangle numbers)
The \( n^{th} \) term of the sequence of triangle numbers is given by, \( t_{n} = \frac{1}{2} 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 = t_{10}\). 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?
In Python:
import time
startTime = time.time()
f = open("./PE42_words.txt", 'r')
dataSet = [strWord[1: -1] for strWord in f.read().split(",")]
f.close()
count = 0
triNumList = [int(0.5 * n * (n + 1)) for n in range(1, 100)]
for data in dataSet:
lenData = len(data)
sumAscii = 0
for i in range(lenData):
sumAscii += ord(data[i]) - 64
if sumAscii in triNumList:
count += 1
print(count)
print(time.time() - startTime, "seconds")
Run time: 0.0182950496673584 seconds
In Java:
package project_euler41_50;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Euler42 {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
int count = 0;
String data[];
ArrayList<Integer> triNumList = new ArrayList<Integer>();
ArrayList<String> dataList = new ArrayList<String>();
BufferedReader br = new BufferedReader (new FileReader("./Euler42_words.txt"));
while(true) {
String line = br.readLine();
if (line == null) break;
data = line.split(",");
for (int i = 0; i < data.length; i++) {
dataList.add(data[i].substring(1, data[i].length() - 1));
}
}
br.close();
for (int i = 1; i < 100; i++) {
triNumList.add((int)(0.5 * i * (i + 1)));
}
for (String word : dataList) {
int lenWord = word.length();
int sumAscii = 0;
for (int i = 0; i < lenWord; i++) {
sumAscii += word.charAt(i) - 64;
}
if (triNumList.contains(sumAscii)) {
count ++;
}
}
System.out.println(count);
long endTime = System.currentTimeMillis();
System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
}
}
Run time: 0.016seconds
Solution: 162