Algorithm, Data structure/Solved Algorithmic Problem

Project Euler #22 - Names scores

JaykayChoi 2016. 7. 1. 00:00

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?



출처: https://projecteuler.net/problem=22




영문 이름들이 들어있는 텍스트 파일 names.txt 에 있는 이름들에 각 점수를 매기려고 한다. 먼저 모든 이름을 알파벳 순으로 정렬하고 각 문자열의 알파벳에 해당하는 숫자(A=1, B=2, ..., Z=26)를 모두 더한 후 정렬된 번호를 곱합니다.

names.txt에 들어있는 모든 이름의 점수를 계산하여 더한 값을 구하시오.


간단한 문자열 문제네요.


my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;
 
vector<string> readTxtFile(const string& path)
{
    ifstream file(path);
 
    vector<string> ret;
    string str;
 
    while (getline(file, str, ','))
    {
        str = str.substr(1, str.size() - 2);
        ret.push_back(str);
    }
 
    return ret;
}
 
int sumAlphabeticalValue(const string& str)
{
    int ret = 0;
    for (int i = 0; i < str.size(); i++)
        ret += str[i] - 'A' + 1;
    return ret;
}
 
int main() 
{
    vector<string> names = readTxtFile("names.txt");
    sort(names.begin(), names.end());
 
    ll ret = 0;
    for (int i = 0; i < names.size(); i++)
        ret += ((i + 1* sumAlphabeticalValue(names[i]));
 
    cout << ret << endl;
    system("pause");
    return 0;
}
cs