# Morse code golf

You can read the title of this post as ((Morse code) golf) or as (Morse (code golf)).

Morse code is a sort of approximate Huffman coding of letters: letters are assigned symbols so that more common letters can be transmitted more quickly.

You can read about how well Morse code achieves this design objective here.

But digits in Morse code are kinda strange.

I imagine they were an afterthought, tacked on after encodings had been assigned to each of the letters, and so had to avoid encodings that were already in use.

Here are the assignments: |——-+——-| | Digit | Code | |——-+——-| | 1 | .

—- | | 2 | .

— | | 3 | .

— | | 4 | .

– | | 5 | .

.

| | 6 | -.

| | 7 | –.

| | 8 | —.

| | 9 | —-.

| | 0 | —– | |——-+——-| There’s no attempt to relate transmission length to frequency.

Maybe the idea was that all digits are equally common.

While in some contexts this is true, it’s not true in general for mathematical and psychological reasons.

There is a sort of mathematical pattern to the Morse code symbols for digits.

For 1 ≤ n ≤ 5, the symbol for n is n dots followed by 5-n dashes.

For 6 ≤ n ≤ 9, the symbol is n-5 dashes followed by 10-n dashes.

The same rule extends to 0 if you think of 0 as 10.

A more mathematically satisfying way to assign symbols would have been binary numbers padded to five places: 0 -> .

.

1 -> .

– 2 -> .

_.

etc.

Because the Morse encoding of digits is awkward, it’s not easy to describe succinctly.

And here is where golf comes in.

The idea of code golf is to write the shortest program that does some task.

Fewer characters is better, just as in golf the lowest score wins.

Here’s the challenge: Write two functions as small you can, one to encode digits as Morse code and another to decode Morse digits.

Share your solutions in the comments below.

Related posts Lee distance Prefix codes Regex for chemical elements.