Project Euler 22
5000個以上の名前が書かれている46Kのテキストファイルnames.txt を用いる. まずアルファベット順にソートせよ. のち, 各名前についてアルファベットに値を割り振り, リスト中の出現順の数と掛け合わせることで, 名前のスコアを計算する. たとえば, リストがアルファベット順にソートされているとすると, COLINはリストの938番目にある. またCOLINは3 + 15 + 12 + 9 + 14 = 53という値を持つ. よってCOLINは938 × 53 = 49714というスコアを持つ. ファイル中の全名前のスコアの合計を求めよ.
Mathematica
A = Import["mathematica/pe/pedata/pe22.txt", "Text"]; A2 = StringSplit[StringReplace[A, "\"" -> ""], ","]; A3 = Sort[A2]; Total[ Table[ i*Total[ ToCharacterCode[A3[[i]]] - 64 ], {i, Length[A3]} ] ]
ToCharacterCode は文字列をASCIIコードのリストに変換する関数です。
というか、処理自体よりも names.txt を処理できる形に変形する方が苦労しました。
C/C++
#include <iostream> #include <deque> #include <fstream> #include <string> #include <algorithm> #include <boost\algorithm\string.hpp> using namespace std; int main(){ deque<string> dat, dat2; ifstream ifs("dat022_2.txt"); string str; ifs >> str; dat.push_back(str); // datにstrを " または , で区切り格納 boost::algorithm::split(dat, str, boost::is_any_of("\",")); for(int i=0 ; i<(signed)dat.size() ; i++){ if(dat[i]!="") dat2.push_back(dat[i]); } // dat2をソート sort( dat2.begin(), dat2.end() ); int sum=0; char c; int k; for(int i=0 ; i<dat2.size() ; i++){ k=0; for(int j=0 ; j<(signed)dat2[i].size() ; j++){ c = dat2[i].at(j); k += c-64; } sum+=k*(i+1); } cout << sum << endl; int end; cin >> end; return 0; }
includeが多いー。初めてboostを使ってみました。
今回はsortとかsplitとかが使えたのでなんか嬉しい。
それはそうと、VS2010がいろいろ意味不明なエラーを出してきて困り果てました。>>とか<<の演算子の定義が見つかりませんとか言われて。ああ怖い。