39 votes

Programming Challenge: creative FizzBuzz

Pretty standard:

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”.

The twist: come up with the most creative or unusual way to solve this in your language of choice.

92 comments

  1. Ark
    Link
    I only know how to code at a really basic level, but a weekly coding challenge would be quite cool to have on ~comp.

    I only know how to code at a really basic level, but a weekly coding challenge would be quite cool to have on ~comp.

    18 votes
  2. [3]
    kgz
    Link
    Here's one I prepared earlier (python 2.7 only): ''' 124 0 0 100 1 00 22 12 114 30 0 124 0 0 100 02 00 22 12 114 30 0 100 03 00 71 72 110 41 00 124 00 00 100 01 00 22 115 48 00 100 04 00 71 72 110...

    Here's one I prepared earlier (python 2.7 only):

    '''
    124 0 0 100 1    00      22 12 114 30 0     124 0 0 100
    02               00                22              12
    114 30 0         100              03              00
    71               72             110             41
    00               124           00              00
    100              01          00               22
    115              48        00               100
    04               00       71 72 110 23     0 124 0 0 100
    
    
    2 0 22 115        66           00    100 5 0 71 72     110 5 0 124 0
    00        71      72          100             00                00
    83 4 7 24         24           00            19               24
    24        00      24           34          23               65
    26        12      76           74        127             147
    62 2 54 85         22 76 102 105      122 122 98       117 122 122 9
    '''
    
    _ = lambda __, ___: str(bytearray([int(_) for _ in __doc__.split()][__:-___]))
    _.__code__ = type(_.__code__)(1, 1, 2, 67, _(0, 1), (None, 3, 5, _(-9, 1),
        _(-9, 5), _(-5, 1)), (), ('',), '', '', 0, '', (), ())
    for __ in range(1, 100): _(__)
    
    16 votes
    1. [2]
      dpkonofa
      Link Parent
      I'm an idiot. What's going on here? I see numbers with multiples of 3 and multiples of 5 in there. What am I missing?

      I'm an idiot. What's going on here? I see numbers with multiples of 3 and multiples of 5 in there. What am I missing?

      4 votes
      1. Emerald_Knight
        Link Parent
        Nah, you're not an idiot, it's just really obfuscated code. It looks like it reads its own source code and does some fuckery with the embedded comment, though I honestly don't know what exactly...

        Nah, you're not an idiot, it's just really obfuscated code. It looks like it reads its own source code and does some fuckery with the embedded comment, though I honestly don't know what exactly that is. Something to do with converting to integer values, then to byte arrays, and then finally to strings, but the details escape me.

        Code golf and code obfuscation really aren't my cup of tea and certainly not my area of expertise, so unfortunately this is about as much insight as I can give you.

        4 votes
  3. [9]
    TeaBagTwat
    Link
    Ok, I cant code but my god can I excel. So I did. Image of my final outcome. I used this formula in each cell (where A24, in this case, is the cell number):...

    Ok, I cant code but my god can I excel. So I did.
    Image of my final outcome.

    I used this formula in each cell (where A24, in this case, is the cell number):
    =IF(AND(MOD(A24,4)=0,(MOD(A24,3)=0)),"FizzBuzz",IF(MOD(A24,3)=0,"Fizz",IF(MOD(A24,4)=0,"Buzz",A24)))

    MOD(A24,4)=0 Essentially asks do you get 0 when you divide cell A24 by 4? If you do it must mean it is a multiple of 4. I use this basic way of finding out if it is a muiltiple as the basic for the rest of it. I use an 'and' statement to check first of all if it is a muiltple of both if it's not it tries the other two individually.

    Essentially It is one big if statement. In laymen's terms, it's asking Is this cell divisible by 4 and 3? If so return "FizzBuzz", if not is it divisible by 3? If so return "Fizz", if not is it divisible by 4? If it is return "Buzz" if not just what value is the cell.

    15 votes
    1. [4]
      kgz
      Link Parent
      To be fair, I'd count that as coding.

      To be fair, I'd count that as coding.

      18 votes
      1. [2]
        TeaBagTwat
        Link Parent
        Silicon Valley here I come.

        Silicon Valley here I come.

        11 votes
        1. crius
          Link Parent
          Man, you opened with a bad topic (jokes) but I'm not failing to giggle at every comment you write :D

          Man, you opened with a bad topic (jokes) but I'm not failing to giggle at every comment you write :D

          4 votes
      2. dpkonofa
        Link Parent
        Excel is Turing complete so it's definitely coding.

        Excel is Turing complete so it's definitely coding.

        5 votes
    2. [3]
      sid
      Link Parent
      If you're interested in learning to code, it's a small (purely syntactical) jump from what you already know.

      If you're interested in learning to code, it's a small (purely syntactical) jump from what you already know.

      6 votes
      1. crius
        Link Parent
        The big change is basically learning to keep in mind the structure you're building and learn how to output the final result the way you want.

        The big change is basically learning to keep in mind the structure you're building and learn how to output the final result the way you want.

        2 votes
      2. crius
        Link Parent
        The big change is basically learning to keep in mind the structure you're building and learn how to output the final result the way you want.

        The big change is basically learning to keep in mind the structure you're building and learn how to output the final result the way you want.

    3. Isaac
      Link Parent
      I just gave this problem a shot in Excel and came to same solution as you. I did consider using another IF(MOD(ref,15)=0) instead of the AND(), since 15 is the lowest common multiple. On the one...

      I just gave this problem a shot in Excel and came to same solution as you. I did consider using another IF(MOD(ref,15)=0) instead of the AND(), since 15 is the lowest common multiple.

      On the one hand, a shorter formula always looks more elegant. On the other hand, that's using knowledge calculated outside the program, which feels like bad practice to me. What does everyone else think?

  4. [4]
    ruspaceni
    Link
    I've been wanting to see how hackable quines are and came up with this just now. /* Self-printing program by Joseph Deu Ngoc and mangled by Ruspaceni */ /* Program Number: 0 */ #define MAXPROGRAMS...

    I've been wanting to see how hackable quines are and came up with this just now.

    /* Self-printing program by Joseph Deu Ngoc and mangled by Ruspaceni */
    /* Program Number: 0 */
    #define MAXPROGRAMS 100
    
    void main() {
      char a='"';
      char b='\\';
      char c='\n';
      char *d="/* Self-printing program by Joseph Deu Ngoc and mangled by Ruspaceni */%c/* Program Number: %d */%c#define MAXPROGRAMS %d%c%cvoid main() {%c  char a='%c';%c  char b='%c%c';%c  char c='%cn';%c  char *d=%c%s%c;%c  int e=%d;%c if ((e+1)%%3==0){printf(%c//fizz%%c%c,c);}%c if ((e+1)%%5==0){printf(%c//buzz%%c%c,c);} %cif ((e+1)%%3==0&&(e+1)%%5==0){printf(%c//fizzbuzz%%c%c,c);}%c e=(e+1)%%MAXPROGRAMS;%c  printf(d,c,e,c,MAXPROGRAMS,c,c,c,a,c,b,b,c,b,c,a,d,a,c,e,c,a,a,c,a,a,c,a,a,c,c,c,c,c);%c}%c";
      int e=0;
     if ((e+1)%3==0){printf("//fizz%c",c);}
     if ((e+1)%5==0){printf("//buzz%c",c);} 
    if ((e+1)%3==0&&(e+1)%5==0){printf("//fizzbuzz%c",c);}
     e=(e+1)%MAXPROGRAMS;
      printf(d,c,e,c,MAXPROGRAMS,c,c,c,a,c,b,b,c,b,c,a,d,a,c,e,c,a,a,c,a,a,c,a,a,c,c,c,c,c);
    }
    

    The quine was found on some big listo'quines and looked the most adjustable.
    I can run it with the .bat file:

    "tcc/tcc.exe" -w main.c
    main.exe > main.c
    

    and it'll churn out the source for the next iteration along with the output at the top in a comment.

    I really like quines for some reason and I might start fiddling with them even more. I like the idea of having a quine clock that constantly recompiles and re-runs for each output. But i haven't had much luck with that so far.

    7 votes
    1. [3]
      hightrix
      Link Parent
      I hate to be nitpicky, and I may be wrong here but with this logic: if ((e+1)%3==0){printf("//fizz%c",c);} if ((e+1)%5==0){printf("//buzz%c",c);} This should not be needed. if...

      I hate to be nitpicky, and I may be wrong here but with this logic:

      if ((e+1)%3==0){printf("//fizz%c",c);}
      if ((e+1)%5==0){printf("//buzz%c",c);}
      

      This should not be needed.

      if ((e+1)%3==0&&(e+1)%5==0){printf("//fizzbuzz%c",c);}
      

      For example, e=14 will hit the first 2 if statements printing fizzbuzz then also hit the third with the final line being fizzbuzzfizzbuzz. I'm purposefully ignoring the rest of your solution, as it is pretty neat! :)

      2 votes
      1. [2]
        ruspaceni
        Link Parent
        By all means feel free to nitpick, it's the only way I keep learning. Thanks for pointing that out. I think I spent most of the hour trying to figure out how to perform surgery on the quine and...

        By all means feel free to nitpick, it's the only way I keep learning. Thanks for pointing that out.

        I think I spent most of the hour trying to figure out how to perform surgery on the quine and forgot about what it'd be outputting and whatnot haha

        1 vote
        1. hightrix
          Link Parent
          That's exactly what I figured happened. All of us know many solutions to this problem, so the basics are easy to overlook. Thanks for this solution though, I hadn't looked into quines yet!

          That's exactly what I figured happened. All of us know many solutions to this problem, so the basics are easy to overlook.

          Thanks for this solution though, I hadn't looked into quines yet!

          1 vote
  5. [10]
    SaucedButLeaking
    Link
    I'm an amateur programmer, so I'm mostly proud that it worked on the first try. Then I googled the print_function stuff to clean up the output a little #!/bin/python from __future__ import...

    I'm an amateur programmer, so I'm mostly proud that it worked on the first try. Then I googled the print_function stuff to clean up the output a little

    #!/bin/python
    
    from __future__ import print_function
    
    for num in range(1,100):
    	if num % 3 == 0:
    		print("Fizz",end="")
    	if num % 5 == 0:
    		print("buzz",end="")
    	if num % 3 != 0 and num % 5 != 0:
    		print(str(num),end="")
    	print(" ",end="")
    

    outputs

    [root@host scripts]# python fizzbuzz.py 
    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 [root@host scripts]# 
    
    
    6 votes
    1. [7]
      aphoenix
      (edited )
      Link Parent
      If you want to tighten that up a bit more: for x in range(100): print x%3/2*'Fizz'+x%5/4*'Buzz' or x+1 Just in case you want to work on making something a bit more magical and a bit less readable....

      If you want to tighten that up a bit more:

      for x in range(100): print x%3/2*'Fizz'+x%5/4*'Buzz' or x+1
      

      Just in case you want to work on making something a bit more magical and a bit less readable. Also note: the above only works in Python2 not Python3 (which is not what I would recommend learning).

      Here's a Py3 version:

      print(list(map(lambda i: "Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i), range(1,101))))
      

      Here's a more ridiculous Py3

      print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101)))
      
      4 votes
      1. [6]
        SaucedButLeaking
        Link Parent
        I tend to like readable, but magical can be more efficient and requires a greater understanding, so... In the py2 example, it looks like you're using * as a conditional where it will print eg....

        I tend to like readable, but magical can be more efficient and requires a greater understanding, so...

        In the py2 example, it looks like you're using * as a conditional where it will print eg. 'Fizz' if x%3, but what is the /2 and how does it translate to modulo 0? And why is it /4 in the modulo 5?

        In the first py3 example, you're populating a list with a map of a defined lamda, then printing the list. I again see * as a conditional, but the order is swapped ("print 'Fizz' if i%3==0" rather than "if i%3==0 print 'Fizz'). Is this a py2/py3 difference, or because you're doing it in a lamda?

        I only ask here because I have no idea what I'd be googling. And the "ridiculous" py3 appears beyond me for the moment ("Mmhmm. I understood some of those words")

        1 vote
        1. [5]
          aphoenix
          (edited )
          Link Parent
          In the first py2 example, the division is floor division and the * is string multiplication. Floor or Integer division: in python 2, if you use integers to divide, you'll always get an integer,...

          In the first py2 example, the division is floor division and the * is string multiplication.

          Floor or Integer division: in python 2, if you use integers to divide, you'll always get an integer, and it's the mathematical floor of that divison, ie 75/76 == 0. In python 3, division coerces a float and you need to use the double // to get floor division.

          String multiplication writes the string that number of times. 'Fizz' * 3 gives you 'FizzFizzFizz'.

          Let's consider just the 'Fizz':

          • Take the modulo 3 of x. This will return 0, 1, or 2
          • Divide that number by 2. This will return 0, 0.5, or 1
          • Take the floor of that number. This will return 0, 0, or 1
          • Multiply that number by the string 'Fizz'. This will return '', '', or 'Fizz'
          • If the result is '', then write the current number + 1

          Some real values.

          Set x=0:

          • 0%3 == 0
          • 0/2 == 0
          • floor(0) == 0
          • 0 * 'Fizz' = ''
          • '' is not truthy so print x+1, which is "1"

          Set x = 1:

          • 1%3 == 1
          • 1/2 == 0.5
          • floor(0.5) == 0
          • 0 * 'Fizz' == ''
          • '' is not truthy so print x=1, which is "2"

          Set x=2:

          • 2%3 == 2
          • 2/2 == 1
          • floor(1) == 1
          • 1 * 'Fizz' == 'Fizz'
          • 'Fizz' is truthy so print 'Fizz'

          The same processing works for buzz (it just takes longer to write down), but notice that FizzBuzz will happen automatically because you concatenate the string results together. So '' + '' is still not truthy, but '' + 'Buzz', 'Fizz' + '', and 'Fizz' + 'Buzz' are all truthy.

          The same "trick" is being done in the first Py3 example.

          The second Py3 example is just silly obfuscation; I didn't write it, but I did find it once upon a time in an obfuscation golfing thread. If anyone is unfamiliar with either term:

          • obfuscation -> Making code do something that it looks completely unrelated to
          • golf -> doing whatever task in the shortest amount of code

          Edit: this comment got out of hand.

          1 vote
          1. [4]
            SaucedButLeaking
            Link Parent
            First off, TIL "string multiplication" So if I'm reading this correctly, it works because you're looping through 0-99 and adding 1 at the end so that it's 1-100. This allows the uniqueness of the...

            First off, TIL "string multiplication"

            So if I'm reading this correctly, it works because you're looping through 0-99 and adding 1 at the end so that it's 1-100. This allows the uniqueness of the x%3=2 result to serve as a pseudo-conditional (doubt that's a word, but it makes sense to me, dammit!) via truthiness since adding 1 to any such number gives you a multiple of 3.

            [Edit: what makes " not truthy?]

            1 vote
            1. [3]
              aphoenix
              Link Parent
              That's almost it. The "trick" is that x in this case is not the number that gets displayed. A lot of people see this question as "make a list of numbers from 1 to 100; for each number, check if...

              you're looping through 0-99 and adding 1 at the end so that it's 1-100

              That's almost it.

              The "trick" is that x in this case is not the number that gets displayed. A lot of people see this question as "make a list of numbers from 1 to 100; for each number, check if it's divisible by three, and if it is print Fizz. Otherwise, print that number". But that's not what this one-liner is doing; it's actually testing if the number above whatever the current x is is divisible by 3. This is a minor change, but it makes things much easier to deal with make into a single line of seemingly "magical" code.

              what makes " not truthy?

              A blank string is considered False; a non-blank string is considered True. There are a number of times this can be useful; the concept of "truthiness" in python is pretty great. This stackoverflow answer about Truthiness and Falsiness is pretty succinct.


              I included some later iterations of the one-liner in Python2, just in case that helps. I think they illustrate the slight difference in what we expect to see.

              Consider x = 43, x = 44 and x = 45. If we're looking at the rules of FizzBuzz without looking at this one-liner, we'd say that the result we expect is "when x = 43 or x = 44, the program should print x. When x = 45, the program should print FizzBuzz". But that's not what this program actually does.

              For x = 43 our brain thinks "43 is not divisible by 3 or 5, so print 43", but this program prints 44:

              • 43%3 == 1
              • 1 / 2 == 0
              • 0 * 'Fizz' = ''
              • 43%5 == 3
              • 3 / 4 == 0
              • 0 * 'Buzz' = ''
              • '' + '' == ''
              • '' => not truthy, so print 44

              For x = 44 our brain thinks "44 is not divisible by 3 or 5, so print 44", but this program prints "FizzBuzz":

              • 44%3 == 2
              • 2 / 2 == 1
              • 1 * 'Fizz' = 'Fizz'
              • 44%5 == 4
              • 4/4 == 1
              • 1* 'Buzz' = 'Buzz'
              • 'Fizz' + 'Buzz' == 'FizzBuzz'

              For x = 45 our brain thinks "45 is divisible by 3 and 5, so print FizzBuzz", but this program prints 46:

              • 45%3 == 0
              • 0 / 2 == 0
              • 0 * 'Fizz' = ''
              • 45%5 == 0
              • 0 / 2 == 0
              • 0 * 'Buzz' = ''
              • '' => not truthy so print 46
              1 vote
              1. [2]
                SaucedButLeaking
                Link Parent
                Ah, I was reading " as a character (and therefore a non-blank string) but you had typed '', which is a blank string. Pebkac. It really is a nifty trick. I think I could have worded my...

                Ah, I was reading " as a character (and therefore a non-blank string) but you had typed '', which is a blank string. Pebkac.

                It really is a nifty trick. I think I could have worded my interpretation better as "when x%3=2, x+1 is divisible by 3". Adding +1 at the end when you're printing lets you take advantage of the unique state created when floor dividing (x-1)%n // (n-1) (in that the statement will only evaluate true for x%n=0 . That "trick" doesn't work unless you're iterating over x-1.

                1 vote
                1. aphoenix
                  Link Parent
                  Ah, sorry - the '' was just an empty string. I should have made sure to '' backtick them. And you definitely get it, based on your last paragraph (which is great for someone who identifies as an...

                  Ah, sorry - the '' was just an empty string. I should have made sure to '' backtick them.

                  And you definitely get it, based on your last paragraph (which is great for someone who identifies as an amateur!).

                  1 vote
    2. [2]
      Emerald_Knight
      Link Parent
      A quick note, your solution is just slightly off. range(start, end) will give you a range of integers starting from start inclusive and ending at end exclusive, mathematically represented as...

      A quick note, your solution is just slightly off. range(start, end) will give you a range of integers starting from start inclusive and ending at end exclusive, mathematically represented as [start, end).

      In this case, your solution covers the range from 1 to 99, whereas the expected solution should cover the range from 1 to 100. To fix this, you could do range(100) and perform your operations on num using an offset, i.e. on num + 1, or you could change your range to be range(1, 101).

      The form of your solution is on point, though. Good use of if statement chaining instead of specific if/else cases. A lot of people don't really think of that, so it's a nice touch!

      3 votes
      1. SaucedButLeaking
        Link Parent
        D'oh, that's what I get for not doublechecking!

        D'oh, that's what I get for not doublechecking!

        1 vote
  6. [9]
    Emerald_Knight
    (edited )
    Link
    How about using obnoxious amounts of currying? (function(n) { for(var i = 1; i <= n; i++) { console.log((function(k) { return (function(fizz) { return (function(buzz) { return fizz || buzz ? fizz...

    How about using obnoxious amounts of currying?

    (function(n) {
        for(var i = 1; i <= n; i++) {
            console.log((function(k) {
                return (function(fizz) {
                    return (function(buzz) {
                        return fizz || buzz ? fizz + buzz : k;
                    })(k % 5 == 0 ? 'buzz' : '');
                })(k % 3 == 0 ? 'fizz' : '');
            })(i));
        }
    })(100);
    
    5 votes
    1. [8]
      bee
      Link Parent
      Oof ouch owie my IIFE This is a good one!

      Oof ouch owie my IIFE

      This is a good one!

      2 votes
      1. [7]
        Emerald_Knight
        (edited )
        Link Parent
        Here's a bonus for you using copious amounts of mapping: (function(n) { var i = 0; Array(n).fill(0).map(function(elem) { return ++i; }).map(function(elem) { var fizz = elem % 3 == 0 ? 'fizz' : '';...

        Here's a bonus for you using copious amounts of mapping:

        (function(n) {
            var i = 0;
            Array(n).fill(0).map(function(elem) {
                return ++i;
            }).map(function(elem) {
                var fizz = elem % 3 == 0 ? 'fizz' : '';
                var buzz = elem % 5 == 0 ? 'buzz' : '';
                return fizz || buzz ? fizz + buzz : elem;
            }).map(function(elem) {
                console.log(elem);
            })
        })(100);
        
        3 votes
        1. [6]
          jgb
          Link Parent
          This reminds me of this hilarious post on stackexchange.

          This reminds me of this hilarious post on stackexchange.

          1 vote
          1. [5]
            Emerald_Knight
            Link Parent
            Among the many things I try to teach interns, "try to avoid doing 'clever' things because it will cause you headaches in the future" is one of them. I like to use solid examples, of course, like...

            Among the many things I try to teach interns, "try to avoid doing 'clever' things because it will cause you headaches in the future" is one of them. I like to use solid examples, of course, like the ol' XOR trick for swapping values between two variables without an intermediate third variable.

            3 votes
            1. [4]
              biox
              Link Parent
              Would you consider the XOR trick an example of cleverness?

              Would you consider the XOR trick an example of cleverness?

              1 vote
              1. [3]
                Emerald_Knight
                (edited )
                Link Parent
                Yes, absolutely. It definitely works, but it relies on the more subtle details of how bit manipulation works. If you're unfamiliar with how it works, then you need to do some research and...

                Yes, absolutely. It definitely works, but it relies on the more subtle details of how bit manipulation works. If you're unfamiliar with how it works, then you need to do some research and potentially take the time to prove to yourself that the logic is sound. It takes a lot of mental overhead to verify and maintain just a few lines of code.

                Unless you have a direct need for it, it's far better to use the explicit temporary variable. Even if you do have a genuine need, you should at least document such tricks in detail.

                Granted, the XOR trick is documented well enough and is short enough that it's not too bad, but writing maintainable code requires discipline and allowing yourself to use small tricks here and there will almost inevitably result in those little tricks littering your entire code base and turning it into a mess of technical debt.

                Edit: Also, when a trick like this only really works on int types, doesn't make a significant dent in performance, and is often optimized better by a compiler, it's just a silly trick to use in general.

                1 vote
                1. [2]
                  biox
                  Link Parent
                  Awesome response, thanks for the detail - that makes sense. I tend to conflate idiomatic programming with cleverness sometimes. In Ruby (my primary language) there are tons of shortcuts that the...

                  Awesome response, thanks for the detail - that makes sense. I tend to conflate idiomatic programming with cleverness sometimes. In Ruby (my primary language) there are tons of shortcuts that the community pushes as good practice, and many of these fall into the 'clever' bucket in my mind.

                  edit: for example, it's considered good practice to build arrays using %w[some thing] instead of the standard ['what', 'ever'] structure. A minor example, but it highlights what I'm getting after.

                  1 vote
                  1. Emerald_Knight
                    Link Parent
                    I can definitely see how it would be easy to confuse the two, yeah. If we want to define what being "clever" is more concretely (in the negative sense that we've been using), then I would define...

                    I can definitely see how it would be easy to confuse the two, yeah. If we want to define what being "clever" is more concretely (in the negative sense that we've been using), then I would define it as having two important characteristics:

                    1. Implementing a solution such that you attempt to make some sort of gain (e.g. in performance or code re-usability), but in the process you obscure the behavior of the solution and it requires significant mental overhead to understand how it works.
                    2. Using language-independent constructs in the solution to achieve (1), i.e. the mental overhead should be a problem even for someone well-versed in the language itself.

                    A few common signs that you're (probably) trying to be clever:

                    • You're putting in a lot of effort to make your "optimization" work (shoehorning).
                    • Your alternative solution requires specialized knowledge beyond what is reasonable in order to understand.
                    • There exists a conceptually simpler solution that any reasonable person would have thought about first.
                    • You don't have a genuine need for the alternative solution.
                    • Your alternative solution is more difficult to make changes to than the simpler alternative.

                    Those signs aren't definitive, of course. Sometimes you have to work with less-maintainable solutions in order to make necessary performance gains. Knowing the difference between trying to be "clever" and just working around the limitations of the technology you're working with is a matter of experience.

                    As an aside, experienced Ruby programmers would probably hate me because I would be averse to using a construct like the one you mentioned for string array building. I recognize the use case and I fully understand the motivation, but it seems like something that would be too error-prone and difficult to understand for junior devs in particular. Throw in punctuation and it'll take some serious mental overhead to understand. (Also, I would actually argue that such an idiomatic construct is itself an example of its designer being "clever".)

                    1 vote
  7. [3]
    Luca
    Link
    fn main() { for x in 1..101{ let mut s = String::from(x.to_string()); if x%3 == 0{ s = String::from("fizz"); } if x%5 == 0{ match s.parse(){ Ok(whatever) => { s = String::from("buzz"); whatever },...
    fn main() {
        for x in 1..101{
            let mut s = String::from(x.to_string());
            if x%3 == 0{
                s = String::from("fizz");
            }
            if x%5 == 0{
                match s.parse(){
                    Ok(whatever) => {
                        s = String::from("buzz");
                        whatever
                    },
                    Err(_) => {
                        s = String::from("fizzbuzz");
                        0
                    },
                };
            }
            println!("{}", s)
        }
    }
    

    I just started learning Rust a few days ago, and haven't had much time to dedicate due to work. To my understanding, the match s.parse() has to return a number value, correct? I don't understand why it doesn't compile if I do this instead:

    match s.parse(){
        Ok(_) => {
            s = String::from("buzz");
            0
        },
        Err(_) => {
            s = String::from("fizzbuzz");
            0
        },
    };
    
    4 votes
    1. [2]
      Crespyl
      Link Parent
      The match statement doesn't actually need to return anything, I don't think; you should be able to just do something like: Ok(_) => { s = ... }, Err(_) => { s = ... } The reason it isn't compiling...

      The match statement doesn't actually need to return anything, I don't think; you should be able to just do something like:

      Ok(_) => {
        s = ...
      },
      Err(_) => {
        s = ...
      }
      

      The reason it isn't compiling for you like that is because rustc doesn't know which version of parse() to use. It's a generic function that could return any type, so the compiler needs to either figure out from the context (you returning an integer) or by explicitly stating which version you want like so: match s.parse::<u32>() {

      Having said that, match is an expression and it does return a value, so a common idiom is to make that work for you in situations like this (where you want to assign a variable based on some match).

      s = match s.parse::<u32>() {
        Ok(_) => String::from("buzz"),
        Err(_) => String::from("fizzbuzz")
      }
      

      Now, I'm not convinced String parsing is strictly necessary here, and an informative exercise might be to try doing everything with &str slices instead of (owned, allocating) Strings.

      4 votes
      1. Luca
        Link Parent
        Fantastic explanation, thank you. I didn’t realize parse() was a generic function, so the error messages I was getting make a lot more sense now.

        Fantastic explanation, thank you. I didn’t realize parse() was a generic function, so the error messages I was getting make a lot more sense now.

        1 vote
  8. [9]
    bee
    Link
    Here's one I just made in JS. Output is to the console. for(var i=0,f=!1,b=!1,z=!1;++i<101;f=i%3>1,b=i%5>3,z=f&&b){console.log(z?"FizzBuzz":f?"Fizz":b?"Buzz":i);}

    Here's one I just made in JS. Output is to the console.

    for(var i=0,f=!1,b=!1,z=!1;++i<101;f=i%3>1,b=i%5>3,z=f&&b){console.log(z?"FizzBuzz":f?"Fizz":b?"Buzz":i);}
    
    4 votes
    1. [2]
      hightrix
      Link Parent
      Now that is quite the one liner! Clever :)

      Now that is quite the one liner! Clever :)

      3 votes
      1. bee
        Link Parent
        Thanks! It could definitely be shortened, but I don't think the goal here was the shortest code haha

        Thanks! It could definitely be shortened, but I don't think the goal here was the shortest code haha

    2. [2]
      set
      Link Parent
      You can take it down a few characters by not initializing f, b or z: for(var i=0,f,b,z;++i<101;f=i%3>1,b=i%5>3,z=f&&b){console.log(z?"FizzBuzz":f?"Fizz":b?"Buzz":i);}

      You can take it down a few characters by not initializing f, b or z:

      for(var i=0,f,b,z;++i<101;f=i%3>1,b=i%5>3,z=f&&b){console.log(z?"FizzBuzz":f?"Fizz":b?"Buzz":i);}

      1 vote
      1. bee
        (edited )
        Link Parent
        Nice! I think I was testing this in a strict environment, so that would have never crossed my mind.

        Nice! I think I was testing this in a strict environment, so that would have never crossed my mind.

        1 vote
    3. [4]
      crius
      Link Parent
      On modern browser you can write that in es6+ and use less characters (shorthands and functional programming approach). On mobile right now or I'll write it down, sorry :(

      On modern browser you can write that in es6+ and use less characters (shorthands and functional programming approach).

      On mobile right now or I'll write it down, sorry :(

      1. [3]
        bee
        Link Parent
        What ES6 optimizations could be used in this situation? At least, for this version?

        What ES6 optimizations could be used in this situation? At least, for this version?

        1. [2]
          crius
          Link Parent
          Hey! Nothing, my bad! I was checking from mobile and basically could only see partials of the whole string and thought to have seen a "function(){}" somewhere in that line and of course you could...

          Hey! Nothing, my bad!

          I was checking from mobile and basically could only see partials of the whole string and thought to have seen a "function(){}" somewhere in that line and of course you could have used the shorthand "val=>returned" in that case but I see now that it's quite perfect as it is :)

          2 votes
          1. bee
            Link Parent
            Thanks! I wasn't too sure there was anything to be changed, but my familiarity with the ES6 spec is still a bit rough in places, I thought I had missed something :)

            Thanks! I wasn't too sure there was anything to be changed, but my familiarity with the ES6 spec is still a bit rough in places, I thought I had missed something :)

            1 vote
  9. [9]
    aphoenix
    Link
    How about using something super old? Don't google this and guess what it's written in. IDENTIFICATION DIVISION. PROGRAM-ID. FIZZ-BUZZ. DATA DIVISION. WORKING-STORAGE SECTION. 01 CT PIC 999 VALUE...

    How about using something super old? Don't google this and guess what it's written in.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. FIZZ-BUZZ.
    
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 CT PIC 999 VALUE 1.
       01 FZ PIC 999 VALUE 1.
       01 BZ PIC 999 VALUE 1.
    
       PROCEDURE DIVISION.
       FIZZ-BUZZ-MAIN SECTION.
           PERFORM 100 TIMES
                   IF FZ = 3
                        THEN IF BZ = 5
                           THEN DISPLAY "FizzBuzz"
                           COMPUTE BZ = 0
                           ELSE DISPLAY "Fizz"
                           END-IF
                           COMPUTE FZ = 0
                        ELSE IF BZ = 5
                        THEN DISPLAY "Buzz"
                                COMPUTE BZ = 0
                        ELSE
                                DISPLAY CT
                        END-IF
                END-IF
                ADD 1 TO CT
                ADD 1 TO FZ
                ADD 1 TO BZ
           END-PERFORM
           STOP RUN.
    
    4 votes
    1. [8]
      Luca
      Link Parent
      Good lord is this COBOL in 2018?

      Good lord is this COBOL in 2018?

      5 votes
      1. [4]
        Emerald_Knight
        Link Parent
        At first I thought I was looking at an ancient Egyptian tablet, but on second glance I think you're right, it looks like it predates that.

        At first I thought I was looking at an ancient Egyptian tablet, but on second glance I think you're right, it looks like it predates that.

        5 votes
        1. [3]
          jgb
          Link Parent
          I want to try out this program but my Antikythera mechanism is broken and I haven't gotten around to fixing it.

          I want to try out this program but my Antikythera mechanism is broken and I haven't gotten around to fixing it.

          5 votes
          1. Emerald_Knight
            Link Parent
            This has to be the most educational joke I've seen in a long time.

            This has to be the most educational joke I've seen in a long time.

            4 votes
      2. aphoenix
        Link Parent
        I no longer have a COBOL interpreter, so I had to check online to make sure this actually worked.

        I no longer have a COBOL interpreter, so I had to check online to make sure this actually worked.

        1 vote
      3. [2]
        palpitations
        (edited )
        Link Parent
        You can run COBOL in a modern Windows/Linux environment... Someone at my work apparently had the idea that this counted as modernizing our infrastructure. They then had the idea that modern...

        You can run COBOL in a modern Windows/Linux environment... Someone at my work apparently had the idea that this counted as modernizing our infrastructure.

        They then had the idea that modern anything was too much to hope for, so we're doing COBOL on Server 2008 R2, with a version of the COBOL interpreter that will be out of support by the time the project is ready to go into production.

        The good news is that I had nothing to do with any of that. The bad news is that as soon as it goes into production, the initial blame is going to fall on me if something breaks and people don't get their paychecks. You better believe I've documented the hell out of my objections.

        1 vote
        1. aphoenix
          Link Parent
          There's also this web framework for COBOL: https://github.com/azac/cobol-on-wheelchair (just because it feels like we're talking about ridiculous COBOL things)

          There's also this web framework for COBOL:

          https://github.com/azac/cobol-on-wheelchair

          (just because it feels like we're talking about ridiculous COBOL things)

  10. [3]
    panic
    Link
    Here's a C solution that abuses POSIX printf: int main() { char s[]="\n%n$s\0%1$d"; for(int i=1;i<101;++i) { s[5]=51>(s[2]=50+(0x1241843>>i%15*2&3)); printf(s,i,"","Fizz","Buzz","FizzBuzz"); }...

    Here's a C solution that abuses POSIX printf:

    int main() {
        char s[]="\n%n$s\0%1$d";
        for(int i=1;i<101;++i) {
            s[5]=51>(s[2]=50+(0x1241843>>i%15*2&3));
            printf(s,i,"","Fizz","Buzz","FizzBuzz");
        }
        return 0;
    }
    
    3 votes
    1. [2]
      Pat
      Link Parent
      Can you explain this? I'm a C noob, so I'm getting hung up on what exactly you filled your array with and the hex(?) in the for loop.

      Can you explain this? I'm a C noob, so I'm getting hung up on what exactly you filled your array with and the hex(?) in the for loop.

      2 votes
      1. panic
        (edited )
        Link Parent
        Don't feel bad, this isn't exactly idiomatic C! I was intentionally trying to obfuscate how it works. We need to support the following four behaviors: print a number, print "Fizz", print "Buzz",...

        Don't feel bad, this isn't exactly idiomatic C! I was intentionally trying to obfuscate how it works.

        We need to support the following four behaviors: print a number, print "Fizz", print "Buzz", and print "FizzBuzz". The idea is to use a printf format string as a very limited kind of programming language for selecting what to print. The reason this works is due a somewhat obscure feature of POSIX printf. You can use the syntax n$ in a format string to select the n-th argument. For example, you can use "%2$s" to print the second argument as a string.

        The array s represents the format string. It starts with a newline (so everything isn't bunched up onto one line), and then specifies a string using "%n$s". The character "n" is s[2]—it's assigned a different character each time through the loop. More on that later. Next we have a "\0", which is a NULL byte. This terminates the C string, so the rest of the string isn't used by default. This NULL byte is s[5]. Then we have "%1$d", which simply outputs the first argument as a number.

        Once you understand s, you can start to see what's going on. Our goal is to modify s on each row like this:

        1. s = "\n%2$s\01%1$d"
        2. s = "\n%2$s\01%1$d"
        3. s = "\n%3$s\0%1$d"
        4. s = "\n%2$s\01%1$d"
        5. s = "\n%4$s\0%1$d"

        On lines that we output a number, we set s[2] to '2' (or 50 in ASCII)—this makes the format specifier "%2$s", which prints the second argument, an empty string. On lines that we output "Fizz", we set s[2] to '3' to get "%3$s"—printing the third argument, "Fizz" (and so on with s[2]='4' for "Buzz" and s[2]='5' for "FizzBuzz").

        We use the NULL byte to hide the number on lines where we print "Fizz", "Buzz", or "FizzBuzz". The printf function stops reading the string when it encounters the NULL. On other lines, we set the byte to 1, which represents the "SOH" control character. The printf function will output this character, but the terminal should just ignore it (so you won't actually see it on screen).

        Now, on to the hex number. 0x1241843 in base 4 is 01021001201003—decoding the base 4 digit tells us which string to output. The expression 0x1241843>>i%15*2&3 performs this base-4 decoding, giving us 0, 1, 2, or 3, depending on whether the number should be printed directly, or if we should output "Fizz", "Buzz", or "FizzBuzz".

        Since 50 is the ASCII code for '2', we can add that to the base 4 digit to get the proper value for s[2]. If the result is less than 51, the digit must have been 0, so we use that comparison result to write a 1 or a 0 into s[5].

        Edit: typos.

        2 votes
  11. [3]
    teaearlgraycold
    Link
    32-bit MIPS Assembly: .data fizz: .asciiz "Fizz" buzz: .asciiz "Buzz" line: .asciiz "\n" .text main: li $t0,0 li $t1,101 li $t2,3 li $t3,5 li $t5,0 loop: # $t0 % 3 div $t0,$t2 mfhi $t4 # != 0:...

    32-bit MIPS Assembly:

    .data
    fizz: .asciiz "Fizz"
    buzz: .asciiz "Buzz"
    line: .asciiz "\n"
    
    .text
    main:
        li $t0,0
        li $t1,101
        li $t2,3
        li $t3,5
        li $t5,0
    loop:
        # $t0 % 3
        div $t0,$t2
        mfhi $t4
        # != 0: goto check5
        bgtz $t4,check5
        # set matched flag
        li $t5,1
        # print "Fizz"
        li $v0,4
        la $a0,fizz
        syscall
    check5:
        # t0 % 5
        div $t0,$t3
        mfhi $t4
        # != 0: goto checkneither
        bgtz $t4,checkneither
        # set matched flag
        li $t5,1
        # print "Buzz"
        li $v0,4
        la $a0,buzz
        syscall
    checkneither:
        # check if we've matched yet
        bgtz $t5,newline
        # print i
        li $v0,1
        ori $a0,$t0,0
        syscall
    newline:
        # print "\n"
        li $v0,4
        la $a0,line
        syscall
        # reset matched flag
        li $t5,0
        # increment the iteration variable
        addi $t0,$t0,1
        # Exit if our iteration variable == 101
        bne $t0,$t1,loop
    exit:
        jr $ra
    
    3 votes
  12. [5]
    Gidbinn
    Link
    Fizzbuzz in css using 3 nth-child selectors and pseudo-elements: https://jsfiddle.net/wjbosrxv/

    Fizzbuzz in css using 3 nth-child selectors and pseudo-elements:
    https://jsfiddle.net/wjbosrxv/

    2 votes
    1. [3]
      666
      Link Parent
      I like your approach, but using margin and pixel offsets to adjust the text doesn't look well or properly aligned. I would use list-display: none for all li and CSS counters to generate the...

      I like your approach, but using margin and pixel offsets to adjust the text doesn't look well or properly aligned. I would use list-display: none for all li and CSS counters to generate the numbers to add to the :before pseudo element, that way they will always be aligned with the text. Here's my improved version.

      1 vote
      1. [2]
        Emerald_Knight
        Link Parent
        Just for the hell of it, let's get rid of the hard-coded li tags and use a small piece of JS to add them in. While we're at it, we can bring that total up to 100 to better meet the requirements....

        Just for the hell of it, let's get rid of the hard-coded li tags and use a small piece of JS to add them in. While we're at it, we can bring that total up to 100 to better meet the requirements. Here's my update.

        1 vote
        1. 666
          Link Parent
          Good idea, now it reaches 100 with little effort and the logic still remains in the CSS.

          Good idea, now it reaches 100 with little effort and the logic still remains in the CSS.

    2. Emerald_Knight
      Link Parent
      I never thought to use CSS for this. Neat solution! :)

      I never thought to use CSS for this. Neat solution! :)

  13. 39hp
    (edited )
    Link
    Sorry for zombifying this thread but I was super proud of being able to do one of the challenges! In Python. fizzbuzz=[] for i in range(1,101): if i%15==0: fizzbuzz.append('FizzBuzz') elif i%5==0:...

    Sorry for zombifying this thread but I was super proud of being able to do one of the challenges!

    In Python.

    fizzbuzz=[]
    
    for i in range(1,101):
        if i%15==0:
            fizzbuzz.append('FizzBuzz')
        elif i%5==0:
            fizzbuzz.append('Buzz')
        elif i%3==0:
            fizzbuzz.append('Fizz')
        else:
            fizzbuzz.append(i)
    
    print(fizzbuzz)
    
    2 votes
  14. json
    (edited )
    Link
    ES6 Javascript. Can be executed in Chrome's dev tools console. const GO=( F,i,z,{[z[0 ]]:B},u, zz)=>B((F% u?'':GO[z [u/ u]] ()[z[zz- zz/zz]](u- u,u **u +zz -zz )[z [u] ](z [zz ],'' )[ z[/* **/ zz-...

    ES6 Javascript. Can be executed in Chrome's dev tools console.

    const GO=( F,i,z,{[z[0 ]]:B},u,  zz)=>B((F%      u?'':GO[z  [u/    u]] ()[z[zz-  zz/zz]](u- 
    u,u            **u          +zz       -zz        )[z    [u] ](z    [zz      ],''      )[  
    z[/*           **/         zz-       u/u]        ](u    -u, zz-    u/u     ))+       (F%
    zz?'':GO[z     [u/        u]]       ()[          z[zz-zz/   zz]    ](u    -u,u      **u
    +zz            -zz       )[z       [u]           ](z   [zz  ],''   )[z   [zz       -u/     
    u]]            (zz      -u/       u))            ||F    )|| F<     zz**  u-u      **u      
    +zz        -u?GO(F+1,i ,z,i[z[u- zz/zz]],u       ,zz):null   ;//)[z[z  z-u/u]])[ z[zz-u/u] 
    
    
    GO(1,this,['log', 'toString', 'console', 'replace', 'substring', /[^a-z]/gi],console,3,5);
    

    It does some stupid fuckery to read the parameter names of the GO function and extract the string FizzBuzz from in there. And I just obfuscate some array indices by using u=3 and zz=5 and various maths operations to get 0, 1, 2, 4, 23, and 100.

    2 votes
  15. [2]
    piedpiper
    Link
    I'm not a great programmer, but here I go with javascript: for (var i = 1; i <= 100; i++) { if ((i % 3 == 0) && (i % 5 != 0)) { console.log("fizz"); }; if ((i % 5 == 0) && (i % 3 != 0)) {...

    I'm not a great programmer, but here I go with javascript:

    for (var i = 1; i <= 100; i++) {
    	if ((i % 3 == 0) && (i % 5 != 0)) {
    		console.log("fizz");
    	};
    	if ((i % 5 == 0) && (i % 3 != 0)) {
    		console.log("buzz");
    	};
    	if ((i % 5 == 0) && (i % 3 == 0)) {
    		console.log("fizzbuzz");
    	};
    	if ((i % 5 != 0) && (i % 3 != 0)) {
    		console.log(i);
    	};
    }
    
    1 vote
    1. [2]
      Comment deleted by author
      Link Parent
      1. piedpiper
        Link Parent
        Yes, that's much better. Thanks.

        Yes, that's much better. Thanks.

  16. [3]
    Comment deleted by author
    Link
    1. [2]
      teaearlgraycold
      Link Parent
      If I'm allowed to nitpick, I'd say that c and d aren't great variable names. I'd also recommend using for n in range(amount) instead of while(c < amount). Given that the dictionary is a...

      If I'm allowed to nitpick, I'd say that c and d aren't great variable names. I'd also recommend using for n in range(amount) instead of while(c < amount).

      Given that the dictionary is a generalization made to easily change how the function works, passing it in as an argument would make sense.

      1. [2]
        Comment deleted by author
        Link Parent
        1. Emerald_Knight
          Link Parent
          Bad habits are the bane of every programmer's existence. Trust me when I say that it's far better to crush those bad habits now and build on good habits so that you save yourself massive headaches...

          It's a bad habit since I often forgot to fix it when I'm done with it.

          Bad habits are the bane of every programmer's existence. Trust me when I say that it's far better to crush those bad habits now and build on good habits so that you save yourself massive headaches down the line.

          For example, while it's generally fine to use bad naming for prototyping--or, at least, there's nothing necessarily wrong with it--if you do it in a professional setting then you may find that while you're in the middle of prototyping, your development priorities get changed on you. Then, when you get back to working on that piece of prototyped code from potentially more than a month ago, you'll have to figure out what that code does all over again because of the bad naming that was used.

  17. [2]
    lucyinthesky
    Link
    Sorry, not the most creative way of doing it. In Perl 5: for (1...100) { print "Fizz" x !($_ % 3); print "Buzz" x !($_ % %); print "$_" x !!($_ % 3 and $_ % 5); print "\n"; }

    Sorry, not the most creative way of doing it. In Perl 5:

    for (1...100) {
        print "Fizz" x !($_ % 3);
        print "Buzz" x !($_ % %);
        print "$_" x !!($_ % 3 and $_ % 5);
        print "\n";
    }
    
    1 vote
    1. aphoenix
      Link Parent
      I keep codegolfing in other examples, but I kind of like this for Perl: die+map{(Fizz)[$_%3].(Buzz)[$_%5]||$_}1..100

      I keep codegolfing in other examples, but I kind of like this for Perl:

      die+map{(Fizz)[$_%3].(Buzz)[$_%5]||$_}1..100
      
      1 vote
  18. [3]
    Trait
    Link
    Necroposting, since I'm late to the party: JS can now be abused to the point of looking like if Perl and ML had a baby. Backticks and ${} now act like clumsy brackets, the functional features (and...

    Necroposting, since I'm late to the party:

    JS can now be abused to the point of looking like if Perl and ML had a baby. Backticks and ${} now act like clumsy brackets, the functional features (and let) are lovely, and some pointless esoterica can completely mislead people.

    let hexedron = (_,x,...y) => y[0][x].call(...y);
    let torus = (_,x,...y) => _[0][x].call(...y);
    
    let recur = (f, x, yl) => {
      let [y, ...ys] = yl;
      if(ys.length) {
        return recur(f,f(x,y),ys)
      }
      else {
        return f(x,y)
      }
    }
    
    
    const fizz = 3;
    const buzz = 5;
    const fizzbuzz = fizz * buzz;
    
    let _fizzbuzz = (n) => {
      let strung = hexedron`${'toString'}${n}${fizzbuzz}`;
    
      let f = (x,y) => hexedron`${'replace'}${x}${y[0]}${y[1]}`;
    
      strung = recur(f, strung, [[/.*?([369c0])$/,"fizz $1"],[/(fizz )?(.*?[5a0])$/,"$1buzz"],[/[c3PO#69]/,""]]);
    
      return [strung][~-(0|torus`${"includes"} ${strung} ${"zz"}`)] || n;
    };
    
    let about100 = ~100;
    
    for (let f = -~0; f <- about100; f++) {
      console.log(_fizzbuzz(f));
    }
    
    1 vote
    1. [2]
      Emerald_Knight
      Link Parent
      Don't worry about necroposting. I don't remember which thread it was, but it was noted by @Deimos himself that we have the activity sort for a reason, and that's to encourage posting on older...

      Don't worry about necroposting. I don't remember which thread it was, but it was noted by @Deimos himself that we have the activity sort for a reason, and that's to encourage posting on older threads if we feel like it. Those who don't want to see a post as old as this one can set their activity sort to only show posts up to X age. So feel free to try out any of the other programming challenges if you feel like it!

      As for your submission here, I'm not sure if I should be impressed or horrified! All I can say for sure is, if we're ever working on a team together, please show consideration for my sanity by never issuing a merge request with something like this in it.

      1 vote
      1. Trait
        Link Parent
        That's cool with the activity sort. I came up with the idea for the solution after reading a fizzbuzz thread on /g/ a while back, in which the code got more and more obfuscated with more obscure...

        That's cool with the activity sort.

        I came up with the idea for the solution after reading a fizzbuzz thread on /g/ a while back, in which the code got more and more obfuscated with more obscure languages and features. I hadn't seen anyone in the thread manage a Regex solution, so I made one myself, and because that's too obvious on its own, I also completely mangled the syntax via custom template literals instead of normal function calls. Choosing something like Ook! would be too obviously incomprehensible, but writing incomprehensible code in one of the most widely comprehended languages? Now that is truly art!

        1 vote
  19. [10]
    funsl1ng3r
    Link
    I had just done this for my bootcamp. Here's mine in JavaScript (repl.it = https://repl.it/@nickfp1985/array-index-fizzbuzz ) for (i = 1; i < 100; i++) { if (i % 3 === 0 && i % 5 === 0) {...

    I had just done this for my bootcamp. Here's mine in JavaScript (repl.it = https://repl.it/@nickfp1985/array-index-fizzbuzz )

    for (i = 1; i < 100; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
    console.log('fizzbizz');
    } else if (i % 5 === 0) {
    console.log('fizz');
    } else if (i % 3 === 0) {
    console.log('bizz');
    } else {
    console.log(i);
    }
    }

    1. [8]
      dpkonofa
      Link Parent
      FYI, you can do this quicker if you don't use "else if" statements. Just 3 "if" statements will suffice: if (i%3 === 0) FIZZ if (i%5 === 0) BUZZ if (i%3 !== 0 && i%5 !== 0) NUMBER Any number...

      FYI, you can do this quicker if you don't use "else if" statements. Just 3 "if" statements will suffice:

      if (i%3 === 0) FIZZ
      if (i%5 === 0) BUZZ
      if (i%3 !== 0 && i%5 !== 0) NUMBER

      Any number divisible by both will hit for the first 2, in order and print FIZZBUZZ.

      2 votes
      1. [8]
        Comment deleted by author
        Link Parent
        1. [7]
          dpkonofa
          Link Parent
          Good point. They could just output everything to a string with a += '\n' at the end of the "if" statements and then log the final. Either way, it's possible with fewer conditions.

          Good point. They could just output everything to a string with a += '\n' at the end of the "if" statements and then log the final.

          Either way, it's possible with fewer conditions.

          1. [6]
            json
            (edited )
            Link Parent
            You'd change the if-else for conditional operator and put that inside one console.log for (let n = 1; n <= 100; n++) console.log((n % 3 ? '': 'Fizz') + (n % 5 ? '': 'Buzz') || n); Broken out to...

            You'd change the if-else for conditional operator and put that inside one console.log

            for (let n = 1; n <= 100; n++) console.log((n % 3 ? '': 'Fizz') + (n % 5 ? '': 'Buzz') || n);
            

            Broken out to make it easier to read:

            for (let n = 1; n <= 100; n++) {
              const fizz = (n % 3 ? '': 'Fizz');
              const buzz = (n % 5 ? '': 'Buzz');
              const words = fizz + buzz;
              console.log(words || n);
            }
            

            Also notice I don't use === 0 because 0 is type coerced to false.

            1. [5]
              Emerald_Knight
              (edited )
              Link Parent
              Just so you're aware, that operator--the use of condition ? val_if_true : val_if_false--is called a ternary operator :)

              Just so you're aware, that operator--the use of condition ? val_if_true : val_if_false--is called a ternary operator :)

              1. [4]
                json
                Link Parent
                Yes. But that's because it's the only operator that takes 3 operands. It is called the conditional operator on MDN.

                Yes. But that's because it's the only operator that takes 3 operands. It is called the conditional operator on MDN.

                1 vote
                1. [3]
                  Emerald_Knight
                  Link Parent
                  Fuck, when did people start referring to it as the conditional operator? I've always heard it strictly called the ternary operator to avoid ambiguity with if statements. In any case, I stand...

                  Fuck, when did people start referring to it as the conditional operator? I've always heard it strictly called the ternary operator to avoid ambiguity with if statements.

                  In any case, I stand corrected!

                  1. [2]
                    json
                    Link Parent
                    if statement isn't an operator :p

                    if statement isn't an operator :p

                    1 vote
                    1. Emerald_Knight
                      Link Parent
                      And the word "literally" doesn't mean "figuratively", but somehow people have managed to confuse those to the point of the dictionary definition changing. Some people just don't think about the...

                      And the word "literally" doesn't mean "figuratively", but somehow people have managed to confuse those to the point of the dictionary definition changing. Some people just don't think about the words they're using, and "conditional" is typically the word they pay attention to while ignoring the word "operator". Or, they'll hear "conditional operator" and think of logical operators.

                      The term "conditional operator" may have a strict definition, but it's just ambiguous enough that a lot of people are going to misunderstand what it means. The term "ternary operator", on the other hand, isn't really ambiguous, and while inexperienced devs (or just devs who have known it as the conditional operator from day one, even) may not know it by name at first, they won't easily mistake it for anything else when they hear it in conversation.

                      This is why I find the use of "conditional operator" so surprising. I mean, I get it from the perspective of the term being easier to use and remember, but ambiguity is a pain to deal with in programming.

                      Then again, language has always been a funky subject for me.

                      { "conditional" : "ternary", "ternary" : "conditional", "language" : "wtf" }
                      
    2. Emerald_Knight
      Link Parent
      Pro tip: use three backtick characters `, the same key as the tilde character ~, to enclose your code and get it in that nice monospace style that you see elsewhere in the comments, e.g.: //here...

      Pro tip: use three backtick characters `, the same key as the tilde character ~, to enclose your code and get it in that nice monospace style that you see elsewhere in the comments, e.g.:

      //here is a code comment
      

      Additionally, you can do inline preformatted text by enclosing the text with single backticks, e.g. to get text to look like this.

      Edit: Oh yeah, this also tends to work on some other platforms like Discord and Slack. On Discord, you can even add the name of your target programming language on the same line as the opening backticks to get syntax highlighting for that language!

      2 votes
  20. 666
    Link
    SQL, tested with SQLite 3.24.0: with x(a,n) as ( select 1,1 union all select (case (n+1)%15 when 0 then 'FizzBuzz' else ( case (n+1)%5 when 0 then 'Buzz' else ( case (n+1)%3 when 0 then 'Fizz'...

    SQL, tested with SQLite 3.24.0:

    with x(a,n) as (
      select 1,1
      union all
      select
        (case (n+1)%15
          when 0 then 'FizzBuzz'
          else (
            case (n+1)%5
              when 0 then 'Buzz'
              else (
                case (n+1)%3
                  when 0 then 'Fizz'
                  else n+1
                end)
            end)
        end),
        n+1
      from x where n<100
    )
    select * from x;