您的位置:首页 > 其它

Project Euler Problem 22

2011-03-14 14:10 393 查看
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?

1 #include <iostream>
2 #include <fstream>
3 #include <string>
4 #include <list>
5 using namespace std;
6
7 long GetValue(string s, int index)
8 {
9 long count = 0;
for(string::iterator it=s.begin(); it!=s.end(); it++)
{
if(*it >= 'A' && *it <= 'Z')
{
count += *it - 'A' + 1;
}
}

return count * index;
}

bool compare_nocase(string first, string second)
{
unsigned int i=0;
while ( (i<first.length()) && (i<second.length()) )
{
if(tolower(first[i])<tolower(second[i]))
{
return true;
}
else if(tolower(first[i])>tolower(second[i]))
{
return false;
}
++i;
}

if (first.length()<second.length())
{
return true;
}
else
{
return false;
}
}

int main()
{
ifstream myfile("e:\\names.txt");
string value;
int count = 1;
long long sum = 0;
list<string> names;
while(myfile.good())
{
getline(myfile, value, ',');
names.push_back(value);
//cout << value << endl;
}
names.sort(compare_nocase);

for(list<string>::iterator it=names.begin(); it!=names.end(); it++)
{
sum += GetValue(*it, count++);
}

cout << sum << endl;
cin.get();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: