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?
Here is my solution in C++
#include <iostream> #include <fstream> #include <vector> #include <sstream> std::vector<unsigned long long int> buildTriList(void); int wordToNumb(std::string passedWord); bool triangleCheck(std::vector<unsigned long long int> triList, int passedNumb); std::vector<std::string> readFromFile(std::ifstream &inFile); int main(void) { int triangleCount = 0; std::string filePath = "words.txt"; std::vector<unsigned long long int> triangleList = buildTriList(); std::ifstream inFile(filePath.c_str()); std::vector<std::string> wordList = readFromFile(inFile); for(auto it : wordList) { if(triangleCheck(triangleList, wordToNumb(it))) { triangleCount++; } } std::cout << "There are " << triangleCount << " coded triangle words." << std::endl; return 0; } std::vector<std::string> readFromFile(std::ifstream &inFile) { std::vector fileBuff<std::string>; std::string line; while(std::getline(inFile, line)) { std::stringstream ss(line); std::string szBuff; while(getline(ss, szBuff, ',')) { szBuff.erase(0, 1); szBuff.erase(szBuff.size()-1); fileBuff.push_back(szBuff); } } return fileBuff; } std::vector<unsigned long long int> buildTriList(void) { std::vector<unsigned long long int> triangleList; for(int i = 1; i < 100000; i++) { triangleList.push_back((.5*i)*(i+1)); } return triangleList; } int wordToNumb(std::string passedWord) { int count = 0; for(auto it: passedWord) { count += (static_cast(it)-64); } return count; } bool triangleCheck(std::vector<unsigned long long int> triList, int passedNumb) { for(auto it = triList.begin(); it != triList.end(); it++) { if((*(it)) == passedNumb) { return true; } else if((*(it)) > passedNumb) { return false; } } }