Re.Mark

My Life As A Blog

TF#I Friday #6 : In which I write no F# at all

leave a comment »

I’ve been spending a little time recently writing a simple Windows Phone 7 app and I’ve been impressed with how easy it has been.  I’ve been thinking of writing an anagram solver as an exercise in F# – and it might make for another simple phone app – so I thought I’d start with a few simple steps.

The first step is to try (part of) a potential solution – given a list of words, group the words by the constituent letters (so that, for instance, horse and shore would be grouped together.)  That way, I won’t have to try every single combination of letters and compare against a list of words.  My intention this week was to write a simple program in C# to do this.  Here’s the method that does the work:


private Dictionary<string, List<string>> ProcessWordList(string[] words)
{
    Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();

    foreach (string word in words)
    {
        IOrderedEnumerable<char> ordered = from char a in word.ToCharArray()
                                           orderby a
                                           select a;
        string orderedString = new string(ordered.ToArray());
        if (result.ContainsKey(orderedString))
        {
           result[orderedString].Add(word);
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(word);
            result.Add(orderedString, list);
        }
    }

    return result;
}

Next exercise is either to extend the program towards solving anagrams or to write the method above in F#.

Advertisements

Written by remark

May 27, 2011 at 5:31 pm

Posted in .NET, c#, Development, F#, Languages

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: