The Most Beautiful Code I Ever Wrote

I have been active on various competitive coding sites for over 4 years, and have solved over a thousand different problems, using 40+ different languages.

If you attempt that many problems, you will eventually stumble upon a few where you just find the perfect solution. Or at least solve it so elegantly that it gets upvoted to the top.

I decided to collect some of my most upvoted solutions, where I am also the original author and no one else had the same solution.

Sudoku

Given a 2d array representing a sudoku, validate whether it has been solved correctly:

Example Sudoku
Clojure solution

This is my favourite. It’s simple, elegant, and it looks very obvious, but apparently not that easy to come up with.

It just does exactly what you want:

  • Take every row with board.
  • Take every column with (partition 9 (apply interleave board))
  • Take every square with (map flatten (partition 3 (apply interleave (map #(partition 3 %) board))))
  • Check whether every array is equal to 1..9 when sorted.

Chess

You get a 2d array representing a chess board. Figure out if the white king is in check.

Example chess board

Python solution:

is_check=lambda b:bool(__import__('re').search(r"♔(.{7}|.{11}|.{18}|.{20})♞|♞(.{7}|.{11}|.{18}|.{20})♔|♟(.{8}|.{10})♔|♔(.{9} )*.{9}[♛♜]|[♛♜](.{9} )*.{9}♔|[♛♜] *♔|♔ *[♛♜]|[♛♝]((.{8} )*.{8}|(.{10} )*.{10})♔|♔((.{8} )*.{8}|(.{10} )*.{10})[♛♝]","--".join(map(''.join,b))))

Beautiful code doesn’t have to be readable. Right? At the time I had just solved a “tic tac toe” validation problem using regex, and figured I could use it to solve more complex problems as well. I spent way too much time coming up with this one. And even more time trying to optimise it as much as possible.

How does it work though?

It might look intimidating, but the solution is actually pretty elegant and easy to understand.

If you look at the chess board above and count the squares between the the pawn and the king, you will get 6:

[‘ ‘,’ ‘,’ ‘,’♟’,’1',’2',’3',’4'],
[‘5’,’6',’♔’,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘],

And if you move the pawn to the top left of the king it becomes 8.

[‘ ‘,’♟’,’1',’2',’3',’4',’5',’6'],
[‘7’,’8',’♔’,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘],

Now we know that the king is in check whenever the pawn is 8 or 6 squares to the left of the king.

However, this doesn’t work when the pawn is on the end of the row..

[‘ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’♟’],
[‘1’,’2',’3',’4',’5',’6',’7',’8'],
[‘♔’,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘],

We can solve that by adding two dashes to the end of each row, which makes it 8 and 10 instead.

[‘ ‘,’♟’,’1',’2',’3',’4',’5',’6',’-’,’-’],
[‘9’,’10',’♔’,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’-’,’-’],

If the pawn is on the end now, it will be fine, as there will be 12 squares between.

[‘ ‘,’ ’,’ ',’ ',’ ',’ ',’ ',’♟',’-’,’-’],
[‘3’,’4',’5’,’6‘,’7‘,’8‘,’9‘,’10‘,’-’,’-’],
[‘♔‘,’ ’,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ’,’-’,’-’],

Now just join the arrays to a string and you can write a regular expression to validate:
/♟(.{8}|.{10})♔/

The rook

You can take a similar approach with the rook.

[‘ ‘,’ ’,’♜’,’1‘,’2‘,’3‘,’4‘,’5‘,’-’,’-’],
[‘8‘,’9’,’10‘,’11‘,’12‘,’13‘,’14‘,’15‘,’-’,’-’],
[‘18’,’19‘,’♔’,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’-’,’-’],

If there are 9, 19, 29.. squares between it is check.

But what if there’s a piece between them that blocks check?

We just have to verify that every 10th square between the king and rook is an empty square.

/♜(.{9} )*.{9}♔/ or the other way around /♔(.{9} )*.{9}♜/

You can extrapolate on this idea to create the whole thing.

As short as possible?

After writing the above, I collaborated with some other users to minimise it as much as possible, and we got this in ruby:

Gotta love regular expressions ❤️

Tic tac toe

Here’s my tic tac toe solution that inspired the chess solution, it returns -1 for an unfinished game, 0 for draw, “X” when X wins and “O” when O wins:

ticTacToeWinner=b=>(m=(b=b.map(e=>e.join("")).join("-")).match(/(X|O)((\1\1)|(.{4}\1){2}|(.{3}\1){2})/))?m[1]:/ /.test(b)?-1:0;

Math

Evaluate any mathematical expression that include () / * + -. And you’re obviously not allowed to use eval or similar functions.

Ex: calc('123.45*(678.90 / (---2.5+ 11.5)-(80 -19) *33.25) / 20 + 11') should return -12042.760875

Sometimes writing the most unreadable code ever yields the most upvotes 😄

JavaScript Solution

Coverting seconds to a human readable format

Turn 242062374 into 7 years, 246 days, 15 hours, 32 minutes and 54 seconds. It should be grammatically correct and not return zeros.

Java solution

I don’t really like this solution 🤷 Can you even write beautiful code in Java? However, it’s one of my most upvoted solutions ever and the most upvoted solution to this problem, so maybe you like it. It was written while Java 8 was still pretty new, so perhaps it was upvoted by many people still writing Java 7(I’m sorry).

Reversing an array

Someone on SO asked how you can reverse an array in JS without using reverse(). Some people were a bit confused.

Factor

On my adventure through solving things in 40 different languages, Factor was probably the most entertaining.
I wouldn’t recommend writing this in production, but it’s a pretty fun language to try out. It felt like solving a puzzle.

Can you figure out what this is supposed to solve?

Android dev @shortcut.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store