Monday, 14 October 2019

The Decorator pattern, pragmatism and Glowing Cats

The Decorator Pattern

After a couple of days of engaged debate between colleagues on the matter of the Decorator pattern, and I taking the side to NOT use it for a particular situation, due to it being unnecessary and at risk of becoming an anti-pattern, I was inspired to write a post.

Implementing a pattern for the sake of it without having a real need for it and based on poor judgement on how the code will realistically change over time, is in my opinion, wrong.

The decision to adopt a pattern should always come from a pragmatic mindset.

The Decorator Pattern being an example of this.

The Problem

Most patterns, like the Decorator pattern are designed to solve specific problems. If the problem doesn't exist, then you don't need it, unless you truly anticipate that problem becoming reality.

The YAGNI principle.

The Decorator pattern can be used to combat the problems/limitations of traditional inheritance with a complex hierarchy and multiple layers.

Inheritance is sufficient for simple scenarios, such as below:


Here, you can see an Animal abstract class with a single abstract method called Animate(). The subclasses here are Dog and Cat.


The purpose of the Animate method is for the animal to act out what comes natural to the animal. For example, a dog barks and wags it's tail and a cat meows and purrs (and occasionally attacks you).




For thousands of years, domesticated animals haven't required levels of inheritance beyond this, until recently!

The modern age and it's scientific breakthroughs in gene editing has seen us modifying genes of living organisms using biological nanotechnology, such as CRISPR. 

This, of course, would only ever lead to one thing; GLOWING CATS!


Read more on glowing cats


I know, right?

Now, what if I wanted to edit the glowing cats genes to have red eyes?

And what if I wanted it to wag it's tail?

This means that our inheritance hierarchies will become complex.






These emerging complex inheritance hierarchies would now begin to look like this:



Now, what if I wanted the inheritance to be dynamic, so that it supports all possible combinations inheritance?


What if I wanted to change the order that these genes were edited?


What if I wanted a cat that didn't glow and just had the red eyes and the tail wagging?


Or what if I just wanted the tail wagging?


Or any other permutation you can think of?



The problem with using inheritance for this solution is that the hierarchy is static and declared at compile time.

And because C# doesn't support multiple inheritance that limits us to getting anywhere close to supporting such a dynamic structure.

Therefore simple inheritance is not suitable for scenarios like this, that have several layers of inheritance which might need to be interchangeable.


The Solution


This is where the Decorator pattern comes in.

Thousands of years ago, when the Object Oriented Gods designed the Animal abstract class and it's domesticated Cat and Dog children, they didn't anticipate humans discovering gene editing.

I wouldn't expect them to have already defined a Decorator class. But that's good and they shouldn't have had to, there was no need for it, the problem didn't exist yet.

We now have a need for it, and so we can create it now.

Look at this diagram:




Notice the AnimalDecorator class inheriting from the Animal class. This is the Decorator class.
(Note: Interfaces (e.g. IAnimal) can be used instead of inheritance, but for this example I've kept it an inheritance problem)

The purpose of this class is to chain inheritance together dynamically at runtime.

It does this by being both the Animal, and accepting within it, it's Animal predecessor. (This sounds wiser than intended)

It's subclasses are the various children that would have inherited directly from the Cat class.

Now, this means that at runtime we can dynamically control and alter the hierarchy in any order we can imagine and for whatever purpose is needed. We are no longer bound to the static compile time  inheritance hierarchy.


The Code

void Main()
{  
 var c = new Cat();
 var gc = new GlowingCatDecorator(c);
 var cre = new CatWithRedEyesDecorator(gc);
 var cwt = new CatThatWagsTailDecorator(cre);
 Console.WriteLine(cwt.Animate());
}


 Output












The above code shows the beauty of the Decorator pattern, in that we have the complete freedom to extend behaviour in any way we see fit, rather than being limited to a static inheritance hierarchy.


class AnimalDecorator : Animal
{
 private Animal _animal;

 public AnimalDecorator(Animal animal)
 {
  _animal = animal;
 }

 public override string Animate()
 {  
  return _animal.Animate();
 }
}

The Decorator class is both the Animal, whilst containing the instance of it's animal predecessor. The idea is that we are chaining/extending behaviour together.


class GlowingCatDecorator : AnimalDecorator
{
 public GlowingCatDecorator(Animal animal): base(animal){} 

 public override string Animate()
 {
  var a = base.Animate();
  return a + "\n*Glows*";
 }
}

class CatWithRedEyesDecorator : AnimalDecorator
{
 public CatWithRedEyesDecorator(Animal animal): base(animal){}

 public override string Animate()
 {
  var a = base.Animate();
  return a + "\n*Evil red eyes*";
 }
}

class CatThatWagsTailDecorator: AnimalDecorator
{
 public CatThatWagsTailDecorator(Animal animal): base(animal){}

 public override string Animate()
 {
  var a = base.Animate();
  return a + "\n*Wags tail*";
 }
}

Notice how the concrete classes of the AnimalDecorator are invoking base.Animate(), calling upon the Animal higher up in the inheritance hierarchy chain.

I love this design pattern, it's useful tool for implementing dynamic run-time inheritance. This does not mean you should start implementing it for all your classes in the unlikely case that all your classes will need extension. If you wish to extend a class, most of the time simple inheritance will suffice. If it needs further extension later, and you want those extensions to be dynamic then consider using this pattern.

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.

Tuesday, 26 February 2019

Scrabble (PART 1): How to find all permutations of a string?

Introduction

Scrabble is a popular board game where players attempt to find highest scoring words given a scramble of letters.

My partner is far better at Scrabble than I, but I am a far better programmer than her. Therefore, using my craft of coding, I have built an unscrambler so that I can cheat and be the best Scrabble player in the world.

This post is to show you a (one-of-many) solution to find English words from a scramble letters.

The steps to solve this problem are:
1. Find every permutation of a string
2. Find the highest scoring English words out of all permutations

This post will only be covering step 1. I'll cover step 2 in my next post.

Find Every Permutation of a String

Let's find all permutations of the string "abcd"

To do this, I loop through each character in the string, remove it from the string, and then proceed to place that character in each location within the remainder of the string.

For example:
I remove the first character (a) from the string, leaving the remainder of the string (bcd).

Then I move the character (a) throughout (bcd), and I repeat this for each character in the original string (abcd)

As shown below:

a, bcd
b, acd
c, abd
d, abc
abcd
bacd
cabd
dabc
bacd
abcd
acbd
adbc
bcad
acbd
abcd
abdc
bcda
acdb
abdc
abcd


However, as you may realise, the table above does not contain every permutation of (abcd). This is because the remainder string also needs to be reshuffled in every possible way when placing the character through it.

For example:

(c) (abd)

After moving (c) through (abd), I need to reshuffle (abd) following the same process. As follows:

(a), (bd)

I remove (a) from the string, leaving (bd), and then I move the (a) through the string.

abd
bad
bda
And then for b:

(b), (ad)

bad
abd
adb
etc..

And after each shuffle, I pass the first removed character (c) through it.

The same must also be done for the remainder of the string (bd).

(I hope you get the picture)

(bd) can be reshuffled into two possibilities (bd and db), and there is no need to reshuffle strings any smaller than this.

So, to achieve the recursive behaviour above, we will need to write a recursive method, that is capable of reordering a string, whilst extracting each possible permutation into a result set.

The final result should look like this:

a
ab
abc
abcd
abd
abdc
ac
acb
acbd
acd
acdb
ad
adb
adbc
adc
adcb
b
ba
bac
bacd
bad
badc
bc
bca
bcad
bcd
bcda
bd
bda
bdac
bdc
bdca
c
ca
cab
cabd
cad
cadb
cb
cba
cbad
cbd
cbda
cd
cda
cdab
cdb
cdba
d
da
dab
dabc
dac
dacb
db
dba
dbac
dbc
dbca
dc
dca
dcab
dcb
dcba


The Code

I first create a static class called StringPermutations with one public method:

public static IList<string> GetAllPermutations(this string text)

Note: By using the keyword "this", I am intending to create an extension method.

The goal of this method is to take a string as a parameter and to return a list of all permutations.

Here is the content of that method:


public static IList<string> GetAllPermutations(this string text)
        {
            _finalPermutations = new List<string>();

            GetPermutations(text);

            return _finalPermutations;
        }

There isn't much going on here, we initialise a _finalPermutations field, call a private method called GetPermutations, passing the input string into it and then returning _finalPermutations.

This is where the magick happens:

private static IList<string> GetPermutations(string letters)
        {
            var permutations = new List<string>();
            if (letters.Length == 1)
            {
                if (!_finalPermutations.Contains(letters))
                {
                    _finalPermutations.Add(letters);
                }
                return new List<string> { letters };
            }
            for (int i = 0; i < letters.Length; i++)
            {
                var c = letters[i];
                var remainingLetters = letters.Remove(i, 1);

                var childPermutations = GetPermutations(remainingLetters);

                foreach (var childPermutation in childPermutations)
                {
                    for (int x = 0; x < childPermutation.Length; x++)
                    {
                        var newPermutation = childPermutation.Insert(x, c.ToString());

                        if (!permutations.Contains(newPermutation))
                        {
                            permutations.Add(newPermutation);
                        }

                        if (!_finalPermutations.Contains(newPermutation))
                        {
                            _finalPermutations.Add(newPermutation);
                        }
                    }
                }
            }
            return permutations;
        }

Firstly, I validate the letters parameter and check whether the size of the string is 1. If so, then we have reached the lowest point of recursion. I add the letter to the _finalPermutations list and then return the method, so that we climb back up the recursion ladder.

If the letters parameter has 2 characters or more then we proceed to loop through all characters.

I then remove that character from the string and store the remainder of the string in a variable called remainingLetters
And then using recursion, I self invoke GetPermutations passing the remainder of the string (remainingLetters), in order to find all possibilities of the remaining string.

Once the method returns (which will be once the recursion reaches one character in length), I then loop through each permutation passing the original extracted character at every position, whilst storing the permutation in two result sets. permutations is for returning from the method, passing permutation back up the recursion chain, and _finalPermutations is for storing all permutations.


An Alternative Idea

Another approach suggested by a colleague is to create my own base number system and simply by counting in that base I can create all combinations.

For example:

A string containing 4 characters "abcd".
I create a base 4 number system.
I map each letter to each number in that base
(a=1, b=2. c=3, d=4)
I then count:
1, 2, 3, 4
11, 12, 13, 14
21, 22, 23, 24
31, 32, 33, 34
41, 42, 43, 44
111, 112, 113, 114
etc..

I like the idea and may implement it and share in a blog post some time.


I hope this makes sense, if you wish for me to explain anything then please leave a comment. I'm also interested in your suggestions on how I can improve this code.

In my next post, I will show how I used the Hunspell library (the spellchecker behind OpenOffice) to check each permutation for an English word.


Thanks