Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Tuesday, February 28, 2012

FizzBuzz 15 - Technically Correct (But Oh So Wrong)

I am going to keep with my theme idea for "FizzBuzz" counts.  These solutions are the ones that make your eyes bleed or make you brace for impact.  Technically this solution is correct, but it is oh so wrong.  This solution is in Text.  Not Tex, Text.

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

If you ever interview with me and attempt this answer, be forewarned: I will make you present a complete solution.  Even if it takes the whole time I have allotted.  The only recovery would be to change your answer to a one liner.

However, if you use a specific "interpreter" this is, indeed, source code that will solve the problem. On Linux and Mac one popular solution is cat. More advanced candidates would use mode or less. Those candidates I would send to the IT department to vet (since this is evidence of command line aptitude) but I keep them off of the programming team. The interpreter on Windows is type, and I am not sure where I would send candidates who knew that answer.

Friday, February 24, 2012

#14 - Express Yourself

When creating a new language the designers really need to look at the cool features from current languages and steal the best parts. But you need to be cautious about not just picking up fashions. Remember: fashion is what you look at 20 years later and say "That looks so ugly."

But the reality is that only time will tell what is simply fashion and what is not. One of the cooler features of Ruby is that everything is an expression. Control structures included. That may be why ruby lacks the three expression for loop. That and a mild aversion to semi-colons. I'de post this code in Ruby, except that the new kid on the block is Kotlin, and everyone loves to play with the new kid.

fun main(args : Array<String>) {
  for (i:Int in 1..100) {
    println (
      when (i%15) {
        0 -> "FizzBuzz" 
        5, 10 -> "Buzz"
        3, 6, 9, 12 -> "Fizz"
        else -> i
      })
  }
}

This is only a mild variation from the previous solution. Instead of printing out the results inside the when blocks the whole result of the when block is printed out. Structures like this figure into some of the design decisions like making the case statements only one expression. Evert expression on Kotlin returns a value. Even if it returns Nothing (and there is a language construct for Nothing).

Hopefully the "everything is an expression" thing isn't just fashion.  Ideally when you come back in 20 years (or 20 weeks) and see yourself using control structures as expressions you won't ask yourself  "What was I thinking?"

Tuesday, February 21, 2012

#13 - When in St. Petersberg

That was a short break. Basically I wasn't liking the structure I was forcing myself into. Once I get a large corpus of solutions I can look into formatting, but in the mean time I will focus on stuff that entertains me, free of schedule constraints or themes.

But last Tuesday JetBrains publicly released the beta of Kotlin, their entry into the alternative not-just-JVM languages. There are several very interesting features of this language. And best of all it runs in an IDE I use on a daily basis: IntelliJ Idea. Since this will be the first of several posts, I will first present the solution that most of them will build on.

fun main(args : Array<String>) {
    for (i in 1..100) {
        when (i%15) {
            0 -> println("FizzBuzz");
            5,10 -> println("Buzz");
            3,6,9,12 -> println("Fizz");
            else -> println(i);
        }
    }
}

Instead of a switch statement Kotlin has a when statement (lines 3-8). This is for the most part syntactic sugar, but real sugar not the high fructose code syrup sold to public school programming students. At first blush it looks like changing the word when for switch and some other changes in the case blocks. And in this example, it is all the same. But it is denser and hence reads better.

First, you will not that there is no implicit fall-through. Each case statement matches up to exactly one expression (and that expression can be a multi-expression block). To fall through the rest of the switch you must explicitly use the continue statement. And even then it will simply continue to evaluate itself against the conditions rather than jump to the next block. So the old-school switch drop throughs which were the source of some mysterious bugs are not longer explicitly allowed.

Second, because of the single use structure of the blocks, multiple cases are combined into one comma-separated expression. This is possible because there is no possibility of fall-through between each label.

Finally, the default case (denoted by the else case) is required except in instances when "the compiler can prove that all possible cases are covered with branch conditions".

For this solution, I took advantage of the 15 number pattern in FizzBuzz and simply switched on the mod of 15. There is one case for a FizzBuzz, two for a Buzz, and four for a Fizz. Everything else falls into the else block. This actually reads fairly close to the text description of the problem statement.

The IntelliJ team writing Kotlin is based mostly in Russia. The name Kotlin is from the name of an island near St. Petersberg, which is not really that close to Rome.

Monday, February 13, 2012

This isn't Dr Scholl's, going on hiatus.

This blog project isn't quite "gelling" like I expected it to mentally, so I am going to take a hiatus of indeterminate length. Too many different ideas that don't come down to a focal point just yet. I think the real problem is that I really need to plan all 100 entries into themed blocks, kind of like what I doing with repetition.

The whole Fizz for languages, Buzz for longer elaborations, and FizzBuzz for esoteric languages was a novel setup, the content of the number entries was letting me down.  So if and when I come back to this, I will at least go at it with an entire roadmap (if not text and worked solutions) rather than a rough idea.  However I see this more as a fast paced conference presentation about "Everething you need to know about programming I can show you in FizzBuzz" with 100 variations in 50 minutes, across multiple languages.  But that may be because I prefer speaking to writing.

I do have some code in the hopper that abuses Java language features.  I will post some of those in April as it keeps with the American theme of April Fools Day.

And the title is a reference to a really annoying shoe inserts ad.

Thursday, February 9, 2012

Fizz 12 - A Snake, Hiding in the Whitespace (Python)

For this Fizz, I have decided to tackle one of the other preferred languages at Google: Python. Since there is enough to talk about with Python I decided to do a relatively straight port of the first FizzBuzz I posted.

for i in range(1, 101) :
    if i%15 == 0 :
     print "FizzBuzz"
    elif i%5 == 0 :
     print "Buzz"
    elif i%3 == 0 :
     print "Fizz"
    else :
     print i


Like most "scripting" languages there is not a whole lot of overhead and ceremony in this code sample.  Lots of items are implied via their absence.  The namespace has a nice default, the main procedure to call is simply the statements at the root of the parse tree.  And there is a large set of functions available in the default namespace.

Another unique feature of Python that is white space is significant.  Very significant.  There are no opening and closing braces to group the control structures.  You must indent deeper than that parent control structure and maintain that indentation for multiple statements as a part of that structure.  In essence, the "good practice" of indenting nested control structures is hard wired as a requirement into the grammar of the language.

But the most relevant part of Python in relation to the current subject of discussion is how it loops.  The calculations and decisions in this example are merely syntactical variations of what we have seen before.  Python lacks a three expression loop seen in braces-and-semi-colon languages.  Instead it relies on an "iterator" based loop where the decisions about what the next item is and deciding when to stop is encapsulated inside an object called an Iterator.  In this case, the range function returns an iterator that returns the numbers from one to one hundred in order.  Ignore the fact that the second argument in the function is actually greater than one hundred.  Software is rife with off by one errors.

On last point.  The indentations must be consistent within the control structure.  In other words if you start indenting four more spaces than you had before then each statement in the control structure must have the same amount of indentation.  Whether they be tabs or any number of spaces.  And you can even mix tabs and spaces, if you are consistent.  This example mixes tabs and spaces for the print statements.  So, applying the FizzBuzz hypothesis we can conclude that typical programmers can do indentation consistently.  The real question is if they will (and they won't because everyone has seen enough evidence to the contrary).

Tuesday, February 7, 2012

#11 - Define Recursion: See Recursion

There is one last principal form of repetition remaining to be discussed. This form of repetition is the bane of many first year Computer Science majors and dreaded only more by the professors and TAs who must answer these questions that are best paraphrased as "I just don't get it." That principle? Recursion. I have found no more precise and snarky answer than found in this stackoverflow answer:
If you understand recursion, you're done. Otherwise go read this StackOverflow question...
The link, of course, is back to the very same question.
public class FizzBuzz11 {

  public static void main(String[] arg) {
    recurse(100);
  }

  public static void recurse(int num) {
    if (num > 0) {
      recurse(num - 1);
      if (num % 15 == 0) {
        System.out.println("FizzBuzz");
      } else if (num % 5 == 0) {
        System.out.println("Buzz");
      } else if (num % 3 == 0) {
        System.out.println("Fizz");
      } else {
        System.out.println(num);
      }
    }
  }
}

There are no control structures traditionally associated with repetition in this sample.  No for loops of any stripe, no while or do/while.  Not even a GOTO statement (that would be harmful). What does do the repetition is the call to the recurse method at line 9. That line, of course, is in the very method that it is calling. A snake eating it's own tail.

Of course, a snake will never be able to fully consume itself.  This is assuming it could get over the pain of biting it's own tail, which is about as bad as the anguish felt by many students experiencing their first semester of programming.   At some point things will either hurt too much or the snake's stomach will get too full.  This is called the "base case" where a simple answer is known and we can unwind the stack.

There are a lot of really neat intricacies that can be used with recursion, but this task is much to simple to demonstrate them in this form.  The form used for this recursion is to count backwards (line 10) from the last answer needed (line 4), stop when we hit zero (line 9), and when unwinding the stack calculate the answer for the number at hand (lines 11 to 18).  There is no work done both before and after the recursion, only after.  There is no multiple winding and unwinding of the stack, just one dive in and out.  And there is no use of the returned values from the recursion, in fact there is no return value at all.

All of this aligns with my experience with recursion seen 'in the field.'  Simple recursion can be handled by anyone deserving to be paid market rates.  But you throw in the more interesting cases (as a computer scientist would consider interesting) you are better off shipping it in a binary compiled format.  Because if the typical developer is given a chance to mess with the source code, they will break something.  Until the point they suddenly understand it.

Thursday, February 2, 2012

Buzz 10 - How Many Times?

I'm going to be changing up my plan for Buzz entries.  I had intended on writing 500-1500 essays tangentially related to the FizzBuzz at hand (much like my tiny e-book on Amazon) but I see several problems with it. First, it can ruin the natural progression of solutions if I hold out one solution for a particular post I have planned.  Second, it will ruin the the general feel of this blog, going from technical to random life experiences and then back.  Third, writing that much text on a deadline is kinda hard with my current life balance.  Really, should 1st graders have homework?  Even if it is reading with a parent 20 minutes a night?

So here is the new Buzz plan... for each Buzz I will revisit a language introduced in a previous Fizz entry, and re-work a number entry not in that language using some of the unique features of the language.  For this first entry the selection is limited, but actually relevant to the current numeric theme, especially since Groovy has so many ways to do repitition.

100 times {
  int i = it+1
  if ((i % 3 == 0) && (i % 5 == 0)) {
    println "FizzBuzz"
  } else if (i % 3 == 0) {
    println "Fizz"
  } else if (i % 5 == 0) {
    println "Buzz"
  } else {
    println i
  }
}

Lines one and two are the focus for this post, because the rest of it is a simple transliteration to standard Groovy.

On first reading, it does what it says. Repeat the enclosed block 100 times. But in the syntax sugar and details of the API are some common assumptions. First, what the current count is matters, but there is no explicit variable for that. Each closure without an argument block gets a single variable it that you don't need to declare and just exists. Kind of like this in methods. (And when is some programming language going to introduce that?)

The next assumption is what number to count from. You would think that counting from 1 would be sensible. But Groovy uses zero based arrays, like nearly all popular languages, so instead it starts all couting from zero. Line 2 is an optimization so we don't have to extend our math into the rest of the method.

The rest is pure syntactic sugar. When a symbol that could be a method trails an object with no punctuation it is presumed to be a method call in Groovy. And when a single closure follows a method call, whether or not it is in the argument list, it is added to the argument list of the method. The integer 100 is boxed up to a java.lang.Integer class. And via the Meta-Object-Protocol we can graft in a random times method onto the Ingeger class even though it doesn't exist in the plain JDK.

The end result is something that looks a little bit more like a spoken sentence, but not too close.