Commit fc16e7b5 by Andrew Dahl

Solved Problem 22

parent 8254c6c9
Showing with 48 additions and 0 deletions
Question:
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?
Answer: 871198282
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
char name[256];
int name_sum = 0;
int sum = 0;
vector<string> names;
ifstream ifile;
ifile.open("names.txt");
while(ifile.good())
{
ifile.ignore(1,'"');
ifile.get(name,256,'"');
ifile.ignore(1,',');
names.push_back(name);
}
sort(names.begin(), names.begin()+names.size());
for(int i = 0; i < names.size(); i++)
{
name_sum = 0;
for(int j = 0; j < names[i].size(); j++)
name_sum += names[i][j] - 'A' + 1;
sum += (name_sum * (i+1));
}
cout << sum << endl;
return 0;
}
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment