이경수 선생님의 수학실험실

Problem 22(Names scores) 본문

Project Euler

Problem 22(Names scores)

(이경수) 2019. 4. 14. 20:02

Problem 22(Names scores)

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

 

In Python:

#PE22 Names scores
import time

startTime = time.time()

f = open("./PE22_names.txt", 'r')
dataSet=[strName[1:-1] for strName in f.read().split(",")]
f.close()

dataSet.sort()

sum = 0
for idx1 in range(0, len(dataSet)):
    lenName = len(dataSet[idx1])
    value = 0
    for idx2 in range(0, lenName):
        value += ord(dataSet[idx1][idx2])-64
    sum += value * (idx1 + 1)
print(sum)
print(time.time() - startTime, "seconds")

Run time : 0.03407692909240723 seconds

 

In Java:

//Euler22 Names scores
package project_euler21_30;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class Euler22 {
	public static void main(String[] args) throws IOException {
		long startTime = System.currentTimeMillis();
		int sum = 0;
		int lenName;
		int valueChar;
		String data[];
		ArrayList<String> dataList = new ArrayList<String>();
		BufferedReader br = new BufferedReader (new FileReader("./Euler22_names.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();
		Collections.sort(dataList);
		for (int i = 0; i < dataList.size(); i++) {
			lenName = dataList.get(i).length();
			valueChar = 0;
			for (int j = 0; j < lenName; j++) {
				valueChar += (int) dataList.get(i).charAt(j) - 64;
			}
			sum += valueChar * (i + 1);
		}
		System.out.println(sum);
		long endTime = System.currentTimeMillis();
		System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
	}
}

Run time: 0.029seconds

 

Solution: 871198282

'Project Euler' 카테고리의 다른 글

Problem 24(Lexicographic permutations)  (0) 2019.04.22
Problem 23(Non-abundant sums)  (0) 2019.04.16
Problem 21(Amicable numbers)  (0) 2019.04.14
Problem 20 (Factorial digit sum)  (0) 2019.04.07
problem19 (Counting Sundays)  (0) 2019.02.16
Comments