1. 程式人生 > >Project Euler Problem 42

Project Euler Problem 42

Problem 42 : Coded triangle numbers

The nth term of the sequence of triangle numbers is given by, tn =½n(n+1); so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10

. If the word value is a triangle number then we shall call the word a triangle word.

Using words.txt (right click and ‘Save Link/Target As…’), a 16K text file containing nearly two-thousand common English words, how many are triangle words?

#include <iostream>
#include <cmath>
#include
<vector>
#include <string> #include <fstream> #include <cassert> using namespace std; class PE0042 { private: vector<string> m_wordsVector; void readAllWordsFromFile(char fileName[]); bool checkTriangleNumber(int number); int converteWord2Number(string word)
; public: PE0042() { readAllWordsFromFile("p042_words.txt"); } int getNumOfTriangleWords(); }; void PE0042::readAllWordsFromFile(char fileName[]) { string allWordsStr; ifstream ifp(fileName); ifp >> allWordsStr; int firstQuotePos = 0; string word; for(unsigned int pos=0; pos<allWordsStr.size(); pos++) { if (allWordsStr[pos] == '"') // find Quote { if (0 == firstQuotePos) { firstQuotePos = pos + 1; } else { // secondQuotePos = pos - 1; // count = secondQuotePos-firstQuotePos+1 = pos-firstQuotePos word = allWordsStr.substr(firstQuotePos, pos-firstQuotePos); m_wordsVector.push_back(word); firstQuotePos = 0; } } } ifp.close(); } int PE0042::getNumOfTriangleWords() { int numOfTriangleWords = 0; int number; assert(1 == checkTriangleNumber(55)); assert(0 == checkTriangleNumber(52)); assert(55 == converteWord2Number("SKY")); for (unsigned int i=0; i<m_wordsVector.size(); i++) { number = converteWord2Number(m_wordsVector[i]); if (true == checkTriangleNumber(number)) { numOfTriangleWords ++; } } return numOfTriangleWords; } bool PE0042::checkTriangleNumber(int number) { int n = (int)sqrt((double)number); int tn; while(1) { tn = n*(n+1)/2; if (tn < number) { n++; } else { break; } } if (tn == number) { return true; } else // tn > number { return false; } } int PE0042::converteWord2Number(string word) { int number = 0; for (unsigned int i=0; i<word.size(); i++) { number += word[i]-'A' + 1; } return number; } int main() { PE0042 pe0042; cout << "There are " << pe0042.getNumOfTriangleWords(); cout << " triangle words in words.txt" << endl; return 0; }