Euler Problem 42

The n^(th) term of the sequence of triangle numbers is given by, t_(n) = ½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 = t_(10). 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?

Took a few tries to get the right word value for each entry. Then just compare against a list of Triangle numbers.

import java.util.*;
import java.io.*;

public class Euler42
{
    public static void main(String[] args)
    {
        System.out.format(“Problem 42:\n”);
        Euler42 e = new Euler42();
        System.out.format(“Answer = %s\n”, e.Problem());
    }
    public String Problem ()
    {
        ArrayList<String> W = new ArrayList<String>();
        ArrayList<Integer> T = new ArrayList<Integer>();
        for (int i = 1; i <= 100; i++)
            T.add((int)(0.5*i*(i+1)));
        System.out.format(“%s\n”,T);
        String list= “”, line = “”;
        try
        {
            FileInputStream stream = new FileInputStream(“F:/Development/Java/EULER/src/euler/words.txt”);
            DataInputStream in = new DataInputStream(stream);
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
            while ((line = buffer.readLine()) != null)
                list = line;
            in.close();
        }
        catch (Exception e)
        {
              System.out.print(e+”\n”);
        }
        for (String n : list.split(“,”))
        {
            n = n.substring(1, n.length()-1);
            int sum = 0;
            for (int i = 0; i <= n.length()-1; i++)
                sum += (int)n.charAt(i)-64;
            if (T.contains(sum))
            {
                W.add(n);
                System.out.format(“TRIANGLE: %s = %d\n”,n,sum);
            }
        }
        return String.valueOf(W.size());
    }
}



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s