Vasu Balakrishnan’s Blog

Project Euler #42

leave a comment »

The problem states How many triangle words does the list of common English words contain?

Answer: 162

Solution:  With the help of Extension Methods, I was able to get to this. With LINQ and Functional Programming constructs, it makes it so much easier to implement with few lines of code. Since most of these problems involve generating a sequence of numbers, I wrote a GenerateNumbers that would yield list of numbers based on the Func delegate.

var lContent = ReadFile("Problem42.txt");
var lWords = lContent
    .Replace("\"", "")
    .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

var lAnswer = lWords
    .Where(pArg => pArg.Sum(pCharArg => pCharArg.ToOrdinal()).IsATriangleNumber())

/// Extensions

public static int ToOrdinal(this char pChar)
    return (pChar - 64);

public static bool IsATriangleNumber(this int pNumber)
    return GenerateNumbers(1, pNumber, pInt => pInt * (pInt + 1) / 2)
            .Any(pArg => pArg == pNumber);

public static IEnumerable<T> GenerateNumbers<T>(int pStartIndex, int pEndIndex,
                                                Func<int, T> pFunc)
    foreach (var lNum in Enumerable.Range(pStartIndex, pEndIndex - pStartIndex + 1))
        yield return pFunc(lNum);

Time: 15ms


Written by nbvasu

May 15, 2009 at 12:00 am

Posted in General

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: