I found an interesting question at StackOverflow asking for help finding solution to what I have already mentioned in the title, with PHP. I gave it a try before reading answers and came up with the following code:

That was the first that I could think of. And it worked. The answer given by Dave Chen was much more elegant than my solution (although I think it does something a bit different, but that’s not the point here):

I made a simple benchmark with microtime() and found out that my solution (ran 100k times) took about ~12.3 seconds while Dave’s took only ~7.4 seconds to finish. That makes his code almost twice faster than mine.

Lesson learned: do not stop learning!

If you find this blog useful, you are welcome to make a donation to support it.