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?
C++ source code
#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;
}
Python source code
from urllib.request import urlopen
from math import sqrt
def readAllWordsFromFile():
"""
read all words from file and put them into words list
"""
try:
with open('p042_words.txt') as file_object:
allWordsStr = file_object.read()
except Exception as e:
print(e)
file_url='https://projecteuler.net/project/resources/p042_words.txt'
response = urlopen(file_url)
req = response.read()
allWordsStr = str(req)[2:] # skip b'
words_list = allWordsStr.split(',')
return words_list
def converteWord2Number(word):
"""
converting each letter in a word to a number corresponding to its
alphabetical position and adding these values we form a word value
"""
return sum(ord(c)-ord('A')+1 for c in word)
def checkTriangleNumber(t):
"""
if t is trianger number, then
t = n*(n+1)/2 => n = sqrt(8*t+1) - 1)/2
check whether n is an integer : n % 1 = 0.0
"""
return (sqrt(8*t+1) - 1) / 2 % 1 == 0.0
def getNumOfTriangleWords():
"""
find all triangle words and return the number of triangle words
"""
words_list = readAllWordsFromFile()
numOfTriangleWords = 0
for word in words_list:
number = converteWord2Number(word[1:-1]) #e.g. word='"ABILITY"'
if True == checkTriangleNumber(number):
numOfTriangleWords += 1
return numOfTriangleWords
def main():
assert True == checkTriangleNumber(55)
assert False == checkTriangleNumber(52)
assert 55 == converteWord2Number("SKY")
print("There are",getNumOfTriangleWords(),"triangle words in words.txt")
if __name__ == '__main__':
main()