Started working through Project Euler this weekend.
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?
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <set>
#include <numeric>
#include "PunctFacet.h"
using ThorsAnvil::Util::PunctFacet;
long scoreName(std::string const& name)
{
return std::accumulate(std::begin(name), std::end(name), 0L,
[](long v1, char x){return v1 + x - 'A' + 1;});
}
int main()
{
// Open a file that considers " and , as space and thus ignores them
std::ifstream data;
data.imbue(std::locale(std::locale(), new PunctFacet(std::locale(), "\",")));
data.open("euler/e22.data");
// read all the names in a set (its sorted)
std::set<std::string> names{std::istream_iterator<std::string>(data),
std::istream_iterator<std::string>()};
// Calculate the result
long score = 0;
long loop = 1;
for(auto name: names) {
score += (loop * scoreName(name));
++loop;
}
std::cout << score << "\n";
}
PunctFacet.h
#ifndef THORSANVIL_UTIL_PUNCT_FACET_H
#define THORSANVIL_UTIL_PUNCT_FACET_H
#include <locale>
#include <string>
#include <sstream>
namespace ThorsAnvil
{
namespace Util
{
// This is my facet that will treat the characters in `extraSpace`
// as space characters and thus ignore them with formatted input
class PunctFacet: public std::ctype<char>
{
public:
typedef std::ctype<char> base;
typedef base::char_type char_type;
PunctFacet(std::locale const& l, std::string const& extraSpace)
: base(table)
{
std::ctype<char> const& defaultCType = std::use_facet<std::ctype<char> >(l);
// Copy the default value from the provided locale
static char data[256];
for(int loop = 0;loop < 256;++loop) { data[loop] = loop;}
defaultCType.is(data, data+256, table);
// Modifications to default to include extra space types.
for(auto space: extraSpace) {
table[space] |= base::space;
}
}
private:
base::mask table[256];
};
}
}
#endif
Results
> g++ -O3 -std=c++14 euler/e22.cpp
> time ./a.out
871198282
real 0m0.018s
user 0m0.009s
sys 0m0.007s