One of my favourite ways of improving my coding is by working on Katas. Katas are small coding problems that are used to practise a technique. The concept derives from Japanese martial arts where students continuously repeat a certain sequence to refine their technique. There is an early Playful Python article that goes into this concept more

How do you become better at programming?
You get better at programming just like how you get better at anything else – by practicing. The question is: how to practice in an effective way?

The point of a software kata is not to arrive at a "correct" solution, but as a playground to experiment with different approaches. Since we just learned about the multi-value monad in the previous article, how about we use it to solve the Blackjack scoring kata?

The Kata

One of the key aspects of the game of Blackjack is to determine the score for a hand of cards.

  • Cards from 2 to 10 are worth the points equal to their face value
  • The cards Jack J, Queen Q and King K are worth 10 points each
  • The Ace Ace can be worth either 1 point, or 11 points. Usually the higher the score is better, but if your score crosses 21 then you lose (its called going "bust"). So you want to select the points for the A in such a way that it is as high as possible without crossing 21

Here are some examples of hands and their scores:

  • 2, 5, 7, 2 - 16 points, just add up all the numbers
  • 2, 5, 7, 10 - bust
  • 2, 5, 7, A - 15 points. Here if we take A as 11 then the hand will bust. So we take A as a 1
  • 2, A, A - 14 points. We take the first A as 11 points. Taking the second A as 11 will bust, so we consider the second A as 1 point
  • A, A, A - 13 points

Generally in blackjack you can only consider one A as 11 as any more will definitely bust. However if we keep the bust threshold at a higher value, say 25, then there could be situations where more than one A could be counted as 11.

So here is the problem statement

Given a hand of cards, and a bust threshold, determine the score of the hand

We are going to solve this problem in two ways: one using functions (this article), and the second one using classes (next article). We will use the multi-value monad in both approaches.

Tagged in: