Sunday, 10 March 2019

Scrabble (PART 2): Find the highest scoring English words

Introduction

In Part 1, I had shown you how to get all permutations of a string. Using this, I'll now show you how to find the top scoring English words.

We need to:
1. Check for valid English words.
2. Find the highest scoring English words

Check for valid English words


To check for valid English words against each permutation, I used a library called Hunspell. This is the spellchecker that OpenOffice uses. You simply load it with a dictionary of your choosing, such as British or American English, etc which can then be used for spell checking words from your application.

For .Net Core development, I used a NuGet package called WeCantSpell.Hunspell which is a Hunspell wrapper for .Net Core.

I created an UnsramblerService class which is responsible for handling unscramble requests and returning high scoring words.

public class UnscramblerService
    {
        private WordList _dictionary;

        public UnscramblerService()
        {
            _dictionary = WordList.CreateFromFiles(@"English (British).dic");
        }

        public IList<KeyValuePair<string, int>> Unscramble(string scrambledText)
        {
            var validWords = new List<KeyValuePair<string, int>>();
            var allPermutations = scrambledText.GetAllPermutations();


            foreach (var permutation in allPermutations)
            {
                var result = _dictionary.Check(permutation);
                if (result)
                {                    
                    validWords.Add(ScrabbleScore.GetScore(permutation));
                    validWords.OrderByDescending(x => x.Value);
                }
            }

            return validWords.OrderByDescending(x => x.Value).Take(5).ToList();
        }
    }

WordList is a class that belongs to WeCantSpell.Hunspell. It has a static method (CreateFromFiles) that allow you to return a WordList object representing the English (British) dictionary. You must download the .dic file separately (Many dictionaries are available here: http://wordlist.aspell.net/other-dicts/)

The UnsramblerService has one public method:
public IList<KeyValuePair<string, int>> Unscramble(string scrambledText)
Unscramble takes the scrambled letters as a string and returns a  list of keyvalue pairs that represents the highest scoring words. The string is the word and the int is the score.

In this method, I begin by initialising the validWord list which is used for storing valid words and their scores as I find them. Then I call scrambledText.GetAllPermutations() which a string extension method I created in Part 1. This method returns a list of every single reordered combination a string can possibly be.

Next, I loop over every permutation checking if it is a word or not.  If it is, I determine it's score using ScrabbleScore.GetScore (see next section) which returns a KeyValuePair of the string and it's score which I then add to the ValidWords list.

Once the loop is completed, I order the list by it's score (Value) in descending order and take the 5 highest scoring words (Yes, this shouldn't be hard coded and would be better being parameterised i.e. Unscramble(string scrambledText, int numberOfResults))

Calculating the scores

Below is the implementation behind ScrabbleScore.GetScore.

I use a Dictionary that contains the letter and scrabble score mappings.

GetScore then simply loops through each character in the string, summing the score for each, leaving the total score. I return the original string and the total score as the output.

public class ScrabbleScore
    {
        private static Dictionary<char, int> _scrabbleScores = new Dictionary<char, int>()
        {
            { 'a', 1 },{ 'e', 1},{ 'i', 1 },{ 'o', 1 },{ 'u', 1 }, { 'l', 1 }, { 'n', 1 }, { 's', 1 }, { 't', 1 }, { 'r', 1 },
            { 'd', 2 }, { 'g', 2 },
            { 'b', 3 }, { 'c', 3 },{ 'm', 3 }, { 'p', 3 },
            { 'f', 4 }, { 'h', 4 }, { 'v', 4 }, { 'w', 4 }, { 'y', 4 },
            { 'k', 5 },
            { 'j', 8 }, { 'x', 8 },
            { 'q', 10}, { 'z', 10 }
        };

        internal static KeyValuePair<string, int> GetScore(string word)
        {
            var totalScore = 0;

            foreach (var c in word)
            {
               totalScore +=  _scrabbleScores[c];
            }

            return new KeyValuePair<string, int>(word, totalScore);
        }
    }

I hope you enjoyed this two-part Scrabble solver series.

Please comment with your suggestions or if you'd like to see a similar challenge solved, as I'm hoping to write a Sudoku solver soon, which I expect to be a similar but slightly more difficult challenge.