Two Laptop Bag*
The moose likes Meaningless Drivel and the fly likes The fizz buzz coding challenge Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Other » Meaningless Drivel
Bookmark "The fizz buzz coding challenge" Watch "The fizz buzz coding challenge" New topic
Author

The fizz buzz coding challenge

Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8801
    
    5
More or less "borrowed" from a discussion over at codinghorror...

Your job is to write a small program that prints the numbers from 1 to 100, except:

- when the number is divisible by 3, print "fizz" instead of the number
- when the number is divisible by 5, print "buzz" instead of the number
- when the number is divisible by BOTH 3 and 5 print "fizzbuzz" instead of the number.

That was the original challenge...

The JavaRanch addition is to write the program in such a way that it:

- implements the above
- is meaningfully different than all previous entries
- can somehow be defended as a "good" way to go


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

I'll start off. Mine is not the most obvious solution; it's designed to be easy to generalize. You can easily add any number of new checks that follow the same sort of simple rules, and some simple extensions. I thought about making it even more generalized by providing a sort of priority system, so a particular IChecker can insist on being the only one to run for a certain value, for example. That would complicate things too much, though, and this is already a lot longer than the program needs to be. But I think this strikes a nice balance between "Just the facts, ma'am" and the gold-plated Rube Goldberg treatment. It's a good jumping-off point for many other possible extensions, especially the kind that would lead to the values and patterns being specified as data rather than hard-coded.



[Jess in Action][AskingGoodQuestions]
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81



Bert Bates wrote:- implements the above
- is meaningfully different than all previous entries
- can somehow be defended as a "good" way to go


- Yes, it implements your requirements
- It is meaningfully different from EFH's Java solution
- I define it as good because I understand it, but if someone were to try to use this, they would have to understand and explain why it works, (at which point they might as well write their own code (which will be easier to read / maintain / explain)).


The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8801
    
    5
this is starting off WAY better than I thought it would
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2988
    
    9
Seems like the "can somehow be defended as good" has the most wiggle room for us all. Here's my version, written after seeing the other two:

Ways in which it's good, IMO:
(a) It's written in the standard language of these fora, and thus likely to be readable to everyone.
(b) It avoids overdesign. I like EFH's approach, but it also makes assumptions about what sorts of future changes should be designed for. What if there's a new rule that says if a number is divisible by 7, we should output "bang" and the number? We don't really know what future requirements may hold, so this just sticks to what we know now.
(c) It's pretty short while being fairly clear.
(d) It uses an uncommon style for ternary operators that I feel should be more widely known.

Yes, I'm aware (d) may seem to conflict with (a) and (c) for some people. But I don't care.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2988
    
    9
Alternate performance-uber-alles version:

Of course the performance of all the computation is irrelevant next to the performance of System.out, but oh well.

If we need to start adding more conditions, and if they fit the pattern EFH assumes, then I'd jump to his solution in a heartbeat. But for now, I don't see the need.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2988
    
    9
Short and easily maintainable, with complexity scaling just as well as EFH's code I think (assuming new requirements fit the same pattern he assumes):
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Mike Simmons wrote:Alternate performance-uber-alles version:



Personal extremely picky pet peeve: "i++" is traditional here, and everybody uses it without a thought. But "++i" is simpler at the opcode level and requires no more typing. I realize any optimizer worth two cents will make the difference irrelevant but still, it irks me.
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Mike Simmons wrote:Alternate performance-uber-alles version:
<snip>
Of course the performance of all the computation is irrelevant next to the performance of System.out, but oh well.

If performance is the main consideration, then this can be improved upon by having only a single call to System.out (yes, this does improve speed, although I don't think it is a guaranteed improvement in all OSes):

Perhaps still not optimal - I could precompute the optimal size of the StringBuilder backing store, but that is unlikely to make a big change.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Mike Simmons wrote:(d) It uses an uncommon style for ternary operators that I feel should be more widely known.

Oh Wow! I didn't even know this was possible. Thanks Mike.

One small question, to help me understand this better.
How does this even work? I mean its 4 clauses right? For ternary?


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2988
    
    9
Ernest Friedman-Hill wrote:Personal extremely picky pet peeve: "i++" is traditional here, and everybody uses it without a thought. But "++i" is simpler at the opcode level and requires no more typing. I realize any optimizer worth two cents will make the difference irrelevant but still, it irks me.

Hmmm, both versions compile to exactly the same bytecode for me. Which is consistent with what you said about "any optimizer worth its salt" - I just thought it worth noting that this one is optimized by javac, not the JIT.

javac 1.6.0_24 on a MacBook Pro, for what it's worth.

But hey, irking EFH is another nice bonus.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2988
    
    9
Andrew: interesting point about the single print statement. Though if there's enough output, it may be better to print as you go, rather than saving it all up for the end. Perhaps a BufferedOutputStream or BufferedWriter could be worked into the mix, instead of the StringBuilder.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2988
    
    9
Maneesh: this section

can be viewed as

(I replaced "divisibleBy" with "d" to shorten the lines so we could see the structure more clearly.)
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Mike Simmons wrote:Andrew: interesting point about the single print statement. Though if there's enough output, it may be better to print as you go, rather than saving it all up for the end. Perhaps a BufferedOutputStream or BufferedWriter could be worked into the mix, instead of the StringBuilder.


Good point, but I'll leave that version to the reader to try out.

Maneesh Godbole wrote:I mean its 4 clauses right? For ternary?

Yeah, that's for very large values of two (alternatives).

That's very similar (but more readable) to what I did in my code, where I had all the false statements one after the other ("buzz" : "fizz" : "fizzbuzz").
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

@Mike
Ah! The brackets make it clearer now. Thanks.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3581
    
  14

Andrew Monkhouse wrote:Yeah, that's for very large values of two (alternatives). .


When we get quantum computers I envision a data type 'qubool' that will allow a ternary operator with any number of clauses ;)
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

I felt that lack of support for numbers greater than 2^63-1 was a concern
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

I'd also like to write one that was bitwise, and while I know that a number is divisible by 3 if the sum of the modulus bits are divisible by three I can't think of a similar pattern to use for 'divisible by 5'
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Try to make sense of this one. (Scala with pattern matching).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

I apologize for the length, but here is my fizzbuffy.pl script. Go ahead and run it with "perl fizzbuffy.pl", or whatever you name it as.
edit - i forgot to defend why it's "a good way to go"...Because it's a picture of BUFFY!!!



There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

So the complexity of FizzBuzz in Perl is 7 Buffy's?

Here's a different approach in Scala, in a more functional style. What's better about this one compared to my previous version is that this one is easier to extend if you'd want to check for more numbers.

Suppose that we'd also want to add "bang" when the number is divisible by 7, then in this version I'd just add / change:

In my previous version, I'd have to add more case classes with all combinations of fizz, buzz and bang and expand the cases in all the mapping methods.

(Looks like the code formatter is making some underscores invisible...).
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Introducing FizzBuzz100!

Preloaded (non-dynamic) logic mitigates the risk of unexpected output, while ensuring the source code is easy to read and maintain*.


Also available:
  • FizzBuzz5
  • FizzBuzz25
  • FizzBuzz60 (coming fall 2012)


  • * Within certain undefined parameters.


    "We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
    sscce.org
    David O'Meara
    Rancher

    Joined: Mar 06, 2001
    Posts: 13459

    Solved!
    Bert Bates
    author
    Sheriff

    Joined: Oct 14, 2002
    Posts: 8801
        
        5
    Here's a prototype of a different slant on the "FizzBuzz100". Remember it's just a prototype, but I feel that it could be expanded to solve the entire problem. Yes, yes, it does throw an exception, but after all, it's just a prototype!

    As with the FizzBuzz100, it features "Preloaded (non-dynamic) logic", but the source code is also a bit more compact.


    Hauke Ingmar Schmidt
    Rancher

    Joined: Nov 18, 2008
    Posts: 433
        
        2
    You all are just hacking. No one did specify the process, wrote requirement documents, tells about the team's responsibility structure, there are no unit tests, your solutions don't show any layering, I can't find user stories, no explanation of the build process, I don't see any UML diagrams, no specifications of library dependencies (you don't write Java without supporting frameworks in 2011, do you??), no deployment manual...
    Andrew Monkhouse
    author and jackaroo
    Marshal Commander

    Joined: Mar 28, 2003
    Posts: 11404
        
      81

    A friend of mine who is heavily into Python suggested the following:
    David O'Meara
    Rancher

    Joined: Mar 06, 2001
    Posts: 13459

    Continuing the pre-cached theme

    FizzBuzz2.java


    FizzBuzz3.java


    I consider double braces to be a hack and usually avoid them, but they suffice. An immutable Map/Set would be preferred.
    Both rely on the hash efficiency of java.lang.Integer and avoid storing non fizz/buzz values.
    The second form could be expanded using a Map<Integer, Set><Integer>> to abstract the 3=fizz, 5=buzz and allow other (eg 7=razz) values
    Darryl Burke
    Bartender

    Joined: May 03, 2008
    Posts: 4523
        
        5

    I believe regex should be given a chance ;) So this is different on two counts: use of regex, and leveraging the loop increment instead of using the modulo operator. It's also easily scalable by adding entries to the Map.


    luck, db
    There are no new questions, but there may be new answers.
    Hauke Ingmar Schmidt
    Rancher

    Joined: Nov 18, 2008
    Posts: 433
        
        2
    My percent key is broken and °/. doesn't work so one without modulo.

    Matthew Brown
    Bartender

    Joined: Apr 06, 2010
    Posts: 4343
        
        8

    This was my attempt, written before looking at the others. It's similar to Ernest's approach, in that it's (over)designed for extensibility. Obviously, the rules are going to change at some point, aren't they? In fact, why assume that it will always be factors that are the important point? So there's a general interface that just defines how to produce output for a number, and a concrete implementation class that can take an (ordered) set of factors to test.
    The class that runs the game then has an instance of the interface injected into it by the main method.

    I was tempted to genericise the interface, to avoid assuming that the input are always numbers and the output are always strings...but that's just silly .

    (All put in one file for convenience...wouldn't be in real life)
    Bert Bates
    author
    Sheriff

    Joined: Oct 14, 2002
    Posts: 8801
        
        5
    bump

    It's been almost a year... any new approaches bubbled up?
    Ernest Friedman-Hill
    author and iconoclast
    Marshal

    Joined: Jul 08, 2003
    Posts: 24183
        
      34

    Well, as you say, it's been over a year, we've had time. I can now do a one-liner:

    macduff:~ ejfried$ cat ~/etc/fizzbuzz
    Jesper de Jong
    Java Cowboy
    Saloon Keeper

    Joined: Aug 16, 2005
    Posts: 14074
        
      16

    Scala, using partial functions.
    Jesper de Jong
    Java Cowboy
    Saloon Keeper

    Joined: Aug 16, 2005
    Posts: 14074
        
      16

    Something similar in Haskell.

    Martin Vajsar
    Sheriff

    Joined: Aug 22, 2010
    Posts: 3606
        
      60

    As far as I know, the modern outsourcing approach has not been used yet. Here you are:

    If you don't get the expected output, it's a mistake of the operator, who needs to be replaced, equipped with a calculator, or both.

    To adhere to the rules better, the operator instructions would have to be removed from the program. You'll find them on page 378 of the operations manual.
    Matthew Brown
    Bartender

    Joined: Apr 06, 2010
    Posts: 4343
        
        8

    Obviously, this is a really calculation-intensive operation, and so it makes sense to do the calculations in parallel to take advantage of the 100 core machine it will obviously be running on. So here's a solution in C# using parallel LINQ:
    What? You wanted the numbers 1 to 100 in order?

    (* The ToList is because parallel LINQ enumerables don't have a ForEach method because it implies side effects, which are disapproved of. But List does.)
    Bert Bates
    author
    Sheriff

    Joined: Oct 14, 2002
    Posts: 8801
        
        5
    rofl
    Michael Matola
    whippersnapper
    Ranch Hand

    Joined: Mar 25, 2001
    Posts: 1746
        
        2
    jQuery!

    Jesper de Jong
    Java Cowboy
    Saloon Keeper

    Joined: Aug 16, 2005
    Posts: 14074
        
      16

    Matthew's solution in C# with parallel LINQ inspired me to write one with Java 7's Fork Join framework.
    Julien Meddah
    Greenhorn

    Joined: Mar 30, 2012
    Posts: 1
    Here is my take on it :


    I wouldn't go so far as to call it "good" but it has multiple things going on for it, like :
    - It's short
    - It's in Java.
    - No explicit imports, so it's "pure" Java actually
    - No conditions, only one loop
    - No fancy FP stuff
    - No "FizzBuzz" special case, "Fizz" or "Buzz" only

    But of course you have to decipher the 2d array, recognize "^$" as an empty string regex, pass over some redundancies ...


    [EDIT] Something actually simpler:
     
    wood burning stoves
     
    subject: The fizz buzz coding challenge
     
    Similar Threads
    Need help with Incompatible type error
    Divisibity Test Question
    prime number problem
    Calling static method from main
    Code Challenge