Solving the diamond kata with property-based testing series

  1. How to get started with Property-based Testing in C#
  2. Input generators in property-based tests with FsCheck
  3. First and Last line content
  4. Height equals Width
  5. Outside space symmetry
  6. Symmetry around the vertical axis
  7. Symmetry around the horizontal axis
  8. No padding for input letter row
  9. Letters order

All code samples are available on github


Intro

Last time, we started to explore the properties around the diamond's symmetry and discovered some interesting pattern with the spacing around the diamond.

Symmetry around the vertical axis

If you split the diamond in two with a vertical line right in the middle, you'll discover that it's perfectly symmetric. It feels like a property to me; let's try to model it and write a test.

Diamond_VerticalSymmetry

C# Tests

[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
public Property SymmetricAroundVerticalAxis(char c)
{
    return Diamond.Generate(c).ToArray()
        .All(row =>
        {
            var half = row.Length / 2;
            var firstHalf = row[..half];
            var secondHalf = row[(half + 1)..];
            
            return firstHalf.Reverse().SequenceEqual(secondHalf);
        }).ToProperty();
}

Here we used some built-in methods of the .NET library, which makes these tests simple to read and short to write. Note the use of the new C# 8.0 range operators .. to select subsections of the array. The method to validate symmetry is simple:

  1. Take the first half of a row row[..half]
  2. Take the second half of a row, ignoring the middle character row[(half + 1)..]
  3. Reverse one of the halves and compare the two sequence
  4. Do it for each row

If you are wondering what's [Property(Arbitrary = new[] { typeof(LetterGenerator) })] it's probably because you missed my previous post

Wrapping up

Symmetry is an easy pattern to spot in problems as it's very visual. Can you find any other interesting symmetry? We'll find out next time. Until then, don't forget to subscribe.


Solving the diamond kata with property-based testing series

  1. How to get started with Property-based Testing in C#
  2. Input generators in property-based tests with FsCheck
  3. First and Last line content
  4. Height equals Width
  5. Outside space symmetry
  6. Symmetry around the vertical axis
  7. Symmetry around the horizontal axis
  8. No padding for input letter row
  9. Letters order

All code samples are available on github