• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

The fizz buzz coding challenge

 
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Likes 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.

 
author and jackaroo
Posts: 12200
280
Mac IntelliJ IDE Firefox Browser Oracle C++ Java
  • Likes 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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)).
 
Bert Bates
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
this is starting off WAY better than I thought it would
 
Master Rancher
Posts: 4806
72
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Master Rancher
Posts: 4806
72
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Master Rancher
Posts: 4806
72
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 12200
280
Mac IntelliJ IDE Firefox Browser Oracle C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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?
 
Mike Simmons
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 12200
280
Mac IntelliJ IDE Firefox Browser Oracle C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Mike
Ah! The brackets make it clearer now. Thanks.
 
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 ;)
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I felt that lack of support for numbers greater than 2^63-1 was a concern
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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'
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try to make sense of this one. (Scala with pattern matching).
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Likes 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!!!

 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...).
 
Sheriff
Posts: 11343
Mac Safari Java
  • Likes 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
     
    David O'Meara
    Rancher
    Posts: 13459
    Android Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Solved!
     
    Bert Bates
    author
    Posts: 9050
    21
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.


     
    Rancher
    Posts: 436
    2
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 12200
    280
    Mac IntelliJ IDE Firefox Browser Oracle C++ Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    A friend of mine who is heavily into Python suggested the following:
     
    David O'Meara
    Rancher
    Posts: 13459
    Android Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
     
    Bartender
    Posts: 5167
    11
    Netbeans IDE Opera Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    Hauke Ingmar Schmidt
    Rancher
    Posts: 436
    2
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    My percent key is broken and °/. doesn't work so one without modulo.

     
    Bartender
    Posts: 4568
    9
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 9050
    21
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    bump

    It's been almost a year... any new approaches bubbled up?
     
    Ernest Friedman-Hill
    author and iconoclast
    Posts: 24207
    46
    Mac OS X Eclipse IDE Chrome
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 16084
    88
    Android Scala IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Scala, using partial functions.
     
    Jesper de Jong
    Java Cowboy
    Posts: 16084
    88
    Android Scala IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Something similar in Haskell.

     
    Sheriff
    Posts: 3837
    66
    Netbeans IDE Oracle Firefox Browser
    • Likes 3
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 4568
    9
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 9050
    21
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    rofl
     
    whippersnapper
    Posts: 1843
    5
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    jQuery!

     
    Jesper de Jong
    Java Cowboy
    Posts: 16084
    88
    Android Scala IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Matthew's solution in C# with parallel LINQ inspired me to write one with Java 7's Fork Join framework.
     
    Greenhorn
    Posts: 1
    • Likes 3
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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:
    reply
      Bookmark Topic Watch Topic
    • New Topic