Codegolf session - part 1

Having fun with FizzBuzz and Monalisa

Posted by Vinay on June 10, 2014

The idea behind codegolf

Working in startups can be great for so many reasons. You spend most of your time with a small group of people you trust, and you have a kind of freedom that working in a big corporations don’t seem to offer. Working becomes fun, when the people you work with are wonderful and understanding.

At HealthUnlocked, sometimes we have the luxury of being able to spend some time away from work - a couple of hours, nothing significant. We come together with the most simplest of ideas, and each developer takes that simple idea and make something out of it. Here, I detail those sessions and what came of it

FizzBuzz

For our first idea, we came up with FizzBuzz - an extremely simple idea. You print N numbers, and every time the number is divisible by 3, it’s replaced with Fizz. Every time it’s divisible by 5, Buzz is printed of the number. If the number is divisible by both 3 and 5, you print FizzBuzz. The whole code can be simply summed up in javascript in a few lines:

for(var i = 0; i < 20; i++) {
  if(i % 5 == 0 && i % 3 ==0) 
      console.log("FizzBuzz")        
  else if (i % 5==0) 
      console.log("Buzz") 
  else if (i % 3==0) 
      console.log("Fizz") 
  else 
      console.log(i);
}

This simplicity of the code is exactly what makes it an interesting idea. There are so many posibilities that could come out of it. Of course, just doing exactly what I did above with javascript, while tecnically correct, would be too easy and boring, so I wanted to get a bit creative with it.

I had been playing around with paper.js for a while and when I was told we’d be having a fizzbuzz codegolf, I started thinking of ways to code something fun using paper.js. Here’s what I finally ended up doing. Take a picture - any picture. Analyze the picture pixel by pixel, and calculate how close to being black the pixel is. AKA how much “black” is in the pixel. A pixel with #000 would have a 100% blackness factor, while #fff would have 0%. Do you see what I am getting at, yet? So I take each pixel, make it blue if it’s divisible by 3, red if it’s divisible by 5, and purple if divisible by both 3 and 5. This turned out to be a very bad idea - more because I chose a really large picture of monalisa to process, initially. After some trial and error, I ended up resizing the image within the canvas and grouping a set of pixels. Take a group of 10x10 pixels, calculate the collective blackness factor in the group and apply the same logic.

The final code, and the image, can be viewed here. The page is best viewed at some distance. The size of the rendered circles are proportional to the blackness factor. The darker the pixels are, the larger they are drawn. Even so, the page has to be viewed at least at arm’s legth to see the monalisa behind all the circles!