Sam (l33tminion) wrote,

  • Mood:

Overthinking and Stupid Programmer Tricks

Fizzbuzz is a simple game. Players take turns counting up in sequence from 1, except all multiples of 3 are replaced with "fizz", all multiples of 5 are replaced with "buzz", and all multiples of both are replaced by "fizzbuzz". So players count:
1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz...

This game has become a popular interview question for programmers; it's simple but many self-identified "programmers" don't have the basic problem-solving skills to tackle it. Of course, programmers' sense of humor being what it is, all sorts of odd solutions to the problem have popped up in response. My favorite definition of fizzbuzz(n) is:
['fizzbuzz', 'fizz', 'buzz', n][[n%15,n%3,n%5,0].index(0)]
Aside from being a very weird way of implementing a conditional, this is valid Python and valid Ruby. Nifty!

Dougal Stanton also provided this dramatic solution in Haskall (modified a little for brevity):
import Data.Maybe

fizz = concat $ repeat $ replicate 2 Nothing ++ [Just "Fizz"]
buzz = concat $ repeat $ replicate 4 Nothing ++ [Just "Buzz"]
fizzbuzz = zipWith (maybeWith (++)) fizz buzz
numbers = map (Just . show) [1..]

maybeWith f (Just a) (Just b) = Just (a `f` b) 
maybeWith _ (Just a) Nothing  = Just a
maybeWith _  Nothing (Just b) = Just b
maybeWith _  Nothing Nothing  = Nothing

main = map fromJust $ zipWith (maybeWith const) fizzbuzz numbers
This sort of stuff reminds me of another thing I encountered recently, a regular expresion to "check for primes". The expression in question is:
The first part of this expression matches "" or "1", the vertical bar is a logical or, and the latter part of the expression matches a sequence of two or more ones repeated two or more times. Much less cool than I originally thought it would be, given the title! But it is a regular expression that detects sequences of ones of non-prime length, so you can do the following:
import re
non_prime_length = re.compile(r'^.?$|^(..+?)\1+$',re.DOTALL)
def is_prime(n):
    not non_prime_length.match('X' * n)
That creates a sequence of characters of length n, then checks if the length is prime. This is the sort of thing I'd classify as a "stupid programmer trick", a sort-of clever, not-necessarily-practical, totally silly way of solving a simple problem.

So, to all the programmers out there, what's your favorite stupid programmer trick?

P.S. Incidentally, if you can provide a regular expression such that it actually matches the string representation of only prime (or only non-prime) integers, that would be pretty sweet. A proof that such a thing could not be created would be equally impressive.
Tags: programming, random
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded