DEV Community

Cover image for Answered: What the Heck is Code Golf? ⛳
Andrew Healey
Andrew Healey

Posted on • Edited on • Originally published at healeycodes.com

Answered: What the Heck is Code Golf? ⛳

Usually, code golf means one of two things:

  • The act of shortening a section of code.

  • A wonderfully obscure community on the internet who compete to write very short code. To some, they are seen as a group that 'takes the joke too far' but to me they are artisans.

Code golf challenges are not always about writing the shortest code though. Some competitions score on creativeness. Some questions are even just asking is this possible? — and the results are beautiful. Later on, we'll see a RegEx that only matches itself.

The most common measure for a code golf competition is the amount of bytes the answer requires, generally this can be understood as the number of UTF-8 characters. print('Hello, World!') would be a 22 byte answer. Like golf, the lowest score wins.

For 'Print every ASCII character your program doesn't have', Umbrella is the current leader for JavaScript with 84 bytes — which is relatively long.

// Alerts 'bcdfghijkmnpquvxyz6840'
"!#$%&*+,-13:<=>?@[\]^_`{|}~AERTOWS";alert('BCDFGHIJKMNPQUVXYZ'.toLowerCase()+95*72)
Enter fullscreen mode Exit fullscreen mode

Let's see an extreme example, the GolfScript entry. Language reference here.

# Outputs the remaining ASCII characters
{`),32>^.}.~
Enter fullscreen mode Exit fullscreen mode

GolfScript is quite hard to follow. Most of the time, we write code for humans — not machines. In code golf one writes to score points. The standard programming languages, while often used, can be restrictive. For example, I have never seen a C# or Java answer come top in a shortest-answer-wins challenge.

Esoteric languages

An esoteric language:

Much like mainstream programming languages have evolved over time, so have code golfing languages. These languages are designed with different goals. Some want to be able to write the smallest programs. Some are written just because.

Hexagony is a two-dimensional programming language. Let's take a look at a program that prints 'Hello, World!'. You can run this online at tio.run a.k.a. Try It Online — an open source playground of 636 languages.

   H ; e ;
  l ; d ; *
 ; r ; o ; W
l ; ; o ; * 4
 3 3 ; @ . >
  ; 2 3 < \
   4 ; * /
Enter fullscreen mode Exit fullscreen mode

Intrigued? One of my favorite pieces of code golf writing is the language creator's description of his primality testing program. Reading about these solutions, and experimenting with my own, exercises my problem-solving muscle. It helps me to learn the edges of my languages.

Community

Similar to the open source community, code golf is often a collaborative effort. Languages are developed in the open, and questions will find helpful answers. Competition 'entries' will also receive polite assistance. I remember my first attempt at code golf, I received welcome messages and suggestions for shaving off bytes.

The Programming Puzzles & Code Golf section of StackExchange is the most active code golf community on the internet and this is where you can find many of these languages in use. Esolangs is a community wiki where the most esoteric languages are covered in-depth. The #codegolf tag on Twitter is slow but welcoming.

RegEx that only matches itself

As promised, this post is a fun one. The poster begins by stating that this may well be impossible before elaborating on the challenge. Fortunately, jimmy23013 shows us that not only is this challenge possible but is solvable quite tersely indeed.

# RegEx that only matches itself
# in (PCRE) Perl Compatible Regular Expressions
<^<()(?R){2}>\z|\1\Q^<()(?R){2}>\z|\1\Q>

# A more widely compatible version:
/^\/()(?R){2}\/\z|\1\Q^\/()(?R){2}\/\z|\1\Q/
Enter fullscreen mode Exit fullscreen mode

Is this number prime?

Let's start with a Python answer (59 bytes). It's as naive as prime-checking gets but is creatively short. It demonstrates a typical code golf answer: solve the problem the long way round then apply syntax tricks. (Comments my own).

# take a number via stdin
n=int(input())
# build an array of this number's factors from 1 to n
# if there is only one factor (the number one) then it is prime!
print([i for i in range(1,n)if n%i==0]==[1])
Enter fullscreen mode Exit fullscreen mode

The leading JavaScript answer is a little harder to pick apart.

// Alert true or false given an input number
alert(!/^(?!(..+)\1+$)../.test(prompt()))
Enter fullscreen mode Exit fullscreen mode

The poster tells us that it uses a 'cool unary regex to determine primality'. Further research found this ~5000 word article which explains said RegEx expression. As you've probably started to realize, code golf is like programming in that it's a rabbit hole that doesn't end. But it does get more rewarding the further you dive in.

Elsewhere on the web

JS1k is a JavaScript demo competitive for 'fancy pancy JavaScript demos' that come in under 1024 bytes. They are very visually impressive.

There's also the The International Obfuscated C Code Contest which began in 1984. It's closer to treasure hunting than golf though! Here's a maze generator entry from 1995, by Carlos Duarte (source):

1995/cdua

Honorary shoutouts to two of my favorite esolangs 05AB1E and Jelly. They both place well in challenges and are usually accompanied by well-written explanations which are a great entry point for learning them.


Join 150+ people signed up to my newsletter on programming and personal growth!

I tweet about tech @healeycodes.

Top comments (7)

Collapse
 
tobiassn profile image
Tobias SN

The problem with code golfing is that some people have created their own language to use for it, which means they can add new behavior specific to a single challenge, so any answers they post could be just 1 character, which could allow for thousands of different ‘opcodes’.

Collapse
 
healeycodes profile image
Andrew Healey

That’s a really good point, Tobias. For anyone who may not know, there is a rule that stops languages being developed/edited after a challenge has been posted. But I believe what you’re referring to is where people have thought about the common challenges that do arise and are solving them with 4-5 hard to follow UTF-8 characters. I agree with you on some level that this is a problem. However, there has been an evolution in challenges to match this — questions that specifically make it hard for golfing languages to compete. For instance, Paint Starry Night, objectively. I think as long as people are explaining their process (and language) I remain thoroughly interested. For instance, this Jelly answer to ‘How high can you count’.

Great comment 👍.

Collapse
 
thomasrayner profile image
Thomas Rayner

Code golf is the best way to learn the worst parts of a language :D

Collapse
 
healeycodes profile image
Andrew Healey

Very true!

typeof NaN; // -> 'number' 😀

Collapse
 
zacharypatten profile image
Zachary Patten

Do you by chance have any recommendations for re-occuring C# code golf websites? Most golf websites I see don't support C#. :(

Collapse
 
healeycodes profile image
Andrew Healey

Sorry, I haven't come across any code golf websites where C# is overly popular. Stack Exchange still has a little C# content. Answers on that board are warmly welcomed no matter what the language is 👍

Collapse
 
jessicajhon profile image
jessicajhon

I want to use this code for my website which is related to golf
accessories. How can I use this code for this website? Please do let me know.