Project Euler Problem 42 (C++和Python)

100 篇文章 3 订阅
87 篇文章 1 订阅

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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值