Overclock.net banner
1 - 20 of 23 Posts

Ferrari8608

· Registered
Joined
·
2,003 Posts
Discussion starter · #1 ·
Quote:
Originally Posted by http://c2.com/cgi/wiki?FizzBuzzTest

The "Fizz-Buzz test" is an interview question designed to help filter out the 99.5% of programming job candidates who can't seem to program their way out of a wet paper bag. The text of the programming assignment is as follows:

"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"."
Post your solutions!
Wrap them in a code tag wrapped in a spoiler tag.
Critique others' solutions!


Example:
Code:

Code:
for number in range(1, 101):
    output = str()
    if not number % 3:
        output += 'Fizz'
    if not number % 5:
        output += 'Buzz'
    if not output:
        output = str(number)
    print(output)
 
Here's a JS version that takes advantage of sparse arrays (a bad part of JS I might add)
Code:

Code:
(function (arr, i) {
  for (i = 3; i < 101; i += 3) { arr[i] = "fizz"; }
  for ( i = 5; i < 101; i += 5) { arr[i] = (arr[i] || '' ) + "buzz"; }
  arr.forEach(function (item) { console.log(item); });
}([]));

//minified
(function(a,i){for(i=3;i<101;i+=3)a[i]="fizz";for(i=5;i<101;i+=5)a[i]=(a[i]||'')+"buzz";a.forEach(function(m){console.log(m);});}([]));

And scheme
Code:

Code:
(define (lp i end)
 (if (= 0 (modulo i 3)) (display "fizz"))
 (if (= 0 (modulo i 5)) (display "buzz"))
 (newline) ;will output extraneous newlines
 (if (< i end) (lp (+ 1 i) end) '()))
(lp 1 101)

Python 3/2.7 solution
Code:

Code:
for num in range(1,101):
    out = ''
    if (num % 3) == 0:
        out += "fizz"
    if (num % 5) == 0:
        out += "buzz"
    if out:
        print(out)

Your program's output is wrong under idle (and it also isn't valid python 3 code).
Code:

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

Code:

Code:
for(int count = 1; count < 101; count++) {
      if ((count % 15) == 0) {
           System.out.print("FizzBuzz");
      }
      else if ((count % 3) == 0) {
           System.out.print("Fizz");
      }
      else if ((count % 5) == 0)
            System.out.print("Buzz");
      }
      else {
            System.out.print(count);
      }

      System.out.print("\n");
}
I put more thought into this one and worst case it only hits three conditionals versus 4 above.

Code:

Code:
for(int count = 1; count < 101; count++) {
      if ((count % 3) == 0) {
           System.out.print("Fizz");

           if ((count % 5) == 0) {
                System.out.print("Buzz");
           }
      }
      else if ((count % 5) == 0) {
           System.out.print("Buzz");
      }
      else {
            System.out.print(count);
      }

      System.out.print("\n");
}
 
Discussion starter · #4 ·
Quote:
Originally Posted by hajile View Post

snip
I just realized this a minute ago. That's a result of me coding Python 2 at work and Python 3 at home. I tend to mix them up. It was totally valid Python 2 code.
tongue.gif


It's fixed.
 
Code:

Code:
Enumerable.Range(1, 100).Select(i => i % 3 == 0 && i % 5 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i.ToString()).ToList().ForEach(s => Console.WriteLine(s));

Here's a solution that accomplishes this using only one loop and two If statements, and no Else clauses.
It's not one line though. Also not my best code, it's kinda (very) hacky. But it gives the right output. (Editted to be less hacky) (Edit reverted, because I realized I broke my own rule. Null Coalescing counts as an If)
Code:

Code:
            List<string> list = Enumerable.Range(1, 100).Select(i => " " + i.ToString() + "            ").ToList();
            for (int i = 0; i < 100; i++)
            {
                if ((i + 1) % 3 == 0)
                    list[i] = "Fizz          ";
                if ((i + 1) % 5 == 0)
                    list[i] = list[i].Insert(list[i].IndexOf(" "), "Buzz        ");

                Console.WriteLine(list[i].TrimStart().Substring(0, 8));
            }
 
Here's a version in Common Lisp that takes an arbitrary range and a list containing an arbitrary number of test numbers and phrases.

Code:

Code:
;; Our amazing function'
(defun fizbuz (start end lst)
  (do ((i start (incf i))) ((> i end) T)
      (let ((out ""))
           (dolist (x lst)
                   (if (= 0 (mod i (cdr x)))
                       (setq out (concatenate 'string out (car x)))))
           (if (not (string= "" out))
               (print out))))))
;; call with arbitrary args
(fizbuz 8 1000 '(("fizz" . 3) ("buzz" . 5) ("bazz" . 9) ("bazooka" . 2) ("C-C-C-Combo!!!" . 10)))
 
Code:

Code:
public class Main {

    public static void main(String[] args) {

        for (int num = 1; num < 101; num++) {
            int start = num * num % 3 * 4;
            int end = 8 - (((int)-Math.pow(num, 4) % 5) + 5) % 5;
            System.out.println(start == end ? num + "" : "FizzBuzz".substring(start, end));
        }
    }
}
Code:

Code:
print ("\n".join(["FizzBuzz"[number * number % 3 * 4:8 - -number ** 4 % 5] or str(number) for number in range(1, 101)]))
 
JS
Code:

Code:
function fizzBuzz(){
  for(i = 1 ; i < 101 ; i++){
    console.log( i / 3 % 1 === 0 ? i / 5 % 1 === 0 ? "FizzBuzz" : "Fizz" : i / 5 % 1 === 0 ? "Buzz" : i);
  }
}

First that came to mind
Code:

Code:
function fizzBuzz(){
  for(i = 1 ; i < 101 ; i++){
    if((i / 3) % 1 === 0){
      console.log((i / 5) % 1 === 0 ? "FizzBuzz" : "Fizz");
    }else if((i / 5) % 1 === 0){
      console.log("Buzz");
    }else{
      console.log(i);
    }
  }
}
 
Discussion starter · #10 ·
Code:

Code:
HAI

I HAS A LIMIT ITZ 101
I HAS A FIZZ ITZ "Fizz"
I HAS A BUZZ ITZ "Buzz"
I HAS A NOTHING ITZ ""
I HAS A LOOPZ ITZ 1

IM IN YR LOOP UPPIN YR LOOPZ TIL BOTH SAEM LOOPZ AN LIMIT
  I HAS A THREEMOD ITZ MOD OF LOOPZ AN 3
  I HAS A FIVEMOD ITZ MOD OF LOOPZ AN 5
  I HAS A THING ITZ NOTHING
  BOTH SAEM THREEMOD AN 0, O RLY?
    YA RLY, THING R SMOOSH THING AN FIZZ MKAY
  OIC
  BOTH SAEM FIVEMOD AN 0, O RLY?
    YA RLY, THING R SMOOSH THING AN BUZZ MKAY
  OIC
  BOTH SAEM THING AN NOTHING, O RLY?
    YA RLY, VISIBLE LOOPZ
    NO WAI, VISIBLE THING
  OIC
IM OUTTA YR LOOP

KTHXBYE

Yes, it's a real language. You can test it here: http://repl.it/languages
 
Quote:
Originally Posted by Ferrari8608 View Post

Code:

Code:
HAI

I HAS A LIMIT ITZ 101
I HAS A FIZZ ITZ "Fizz"
I HAS A BUZZ ITZ "Buzz"
I HAS A NOTHING ITZ ""
I HAS A LOOPZ ITZ 0

IM IN YR LOOP UPPIN YR LOOPZ TIL BOTH SAEM LOOPZ AN LIMIT
  I HAS A THREEMOD ITZ MOD OF LOOPZ AN 3
  I HAS A FIVEMOD ITZ MOD OF LOOPZ AN 5
  I HAS A THING ITZ NOTHING
  BOTH SAEM THREEMOD AN 0, O RLY?
    YA RLY, THING R SMOOSH THING AN FIZZ MKAY
  OIC
  BOTH SAEM FIVEMOD AN 0, O RLY?
    YA RLY, THING R SMOOSH THING AN BUZZ MKAY
  OIC
  BOTH SAEM THING AN NOTHING, O RLY?
    YA RLY, VISIBLE LOOPZ
    NO WAI, VISIBLE THING
  OIC
IM OUTTA YR LOOP

KTHXBYE

Yes, it's a real language. You can test it here: http://repl.it/languages
Starts from 0 which prints "FizzBuzz" I HAS A LOOPZ ITZ 0 should be I HAS A LOOPZ ITZ 1
tongue.gif
 
I'm so sorry, I had to be "That Guy", but I would totally turn this in for a job application.

Code:

Code:
def main():
    for i in range(1, 101):
        try:
            print(isFizzBuzz(i, isFizz(i), isBuzz(i)))
        except ValueError:
            "Your fizz can no longer buzz!"

"""isFizz calcuates if the integer n is divisble by 3"""
def isFizz(n):
    FizzList = []
    if (n % 3 == 0):
        FizzList.extend((True, 'Fizz'))
    else:
        FizzList.append(False)
    return (FizzList)

"""isBuzz calculates if the integer n is divisble by 5"""
def isBuzz(n):
    BuzzList = []
    if (n % 5 == 0):
        BuzzList.extend((True, 'Buzz'))
    else:
        BuzzList.append(False)
    return (BuzzList)

"""isFizzBuzz calculates if the integer n is divisble by 3 and 5"""
def isFizzBuzz(n, myFizzList, myBuzzList):
    myFizzList = isFizz(n)
    myBuzzList = isBuzz(n)
    if (myFizzList[0] == True and myBuzzList[0] == True):
        return (myFizzList[1] + myBuzzList[1])
    elif (myFizzList[0] == True and myBuzzList[0] == False):
        return (myFizzList[1])
    elif (myFizzList[0] == False and myBuzzList[0] == True):
        return (myBuzzList[1])
    else:
        return n

main()
 
Quote:
Originally Posted by Blaise170 View Post

This is considered a hard question? I don't consider myself a good programmer at all, but even I found this to be rather benign.
No, it isn't a hard thing to program. However a lot of people claim that they can program in a job interview. This leads to issues of companies hiring people who have to be spoon fed on how to do things when it comes time to work.

It is really just a simple thing to prove that you aren't lying on a job application. As I have known many math/actuarial majors to do in job interviews.
 
Discussion starter · #16 ·
Quote:
Originally Posted by Bobicon View Post

I'm so sorry, I had to be "That Guy", but I would totally turn this in for a job application.

Code:

Code:
def main():
    for i in range(1, 101):
        try:
            print(isFizzBuzz(i, isFizz(i), isBuzz(i)))
        except ValueError:
            "Your fizz can no longer buzz!"

"""isFizz calcuates if the integer n is divisble by 3"""
def isFizz(n):
    FizzList = []
    if (n % 3 == 0):
        FizzList.extend((True, 'Fizz'))
    else:
        FizzList.append(False)
    return (FizzList)

"""isBuzz calculates if the integer n is divisble by 5"""
def isBuzz(n):
    BuzzList = []
    if (n % 5 == 0):
        BuzzList.extend((True, 'Buzz'))
    else:
        BuzzList.append(False)
    return (BuzzList)

"""isFizzBuzz calculates if the integer n is divisble by 3 and 5"""
def isFizzBuzz(n, myFizzList, myBuzzList):
    myFizzList = isFizz(n)
    myBuzzList = isBuzz(n)
    if (myFizzList[0] == True and myBuzzList[0] == True):
        return (myFizzList[1] + myBuzzList[1])
    elif (myFizzList[0] == True and myBuzzList[0] == False):
        return (myFizzList[1])
    elif (myFizzList[0] == False and myBuzzList[0] == True):
        return (myBuzzList[1])
    else:
        return n

main()
You forgot the boilerplate. I would call main with:

Code:

Code:
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()  # Just a newline
        sys.exit()
Also, just wondering as I never see this in Python code, why did you put main at the top?
 
Quote:
Originally Posted by Ferrari8608 View Post

You forgot the boilerplate. I would call main with:

Code:

Code:
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()  # Just a newline
        sys.exit()
Also, just wondering as I never see this in Python code, why did you put main at the top?
Just the way I learned I guess.
 
Quote:
Originally Posted by Ferrari8608 View Post

You forgot the boilerplate. I would call main with:

Code:

Code:
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()  # Just a newline
        sys.exit()
Also, just wondering as I never see this in Python code, why did you put main at the top?
I've always learned that Python has main() up top. Not to say that it's the best way, but it is perfectly viable.
 
Quote:
Originally Posted by Bobicon View Post

Just the way I learned I guess.
It just goes against certain languages with a strict entry point. But in the long run I believe the compiler is smart enough to reorganize the code and be able to float the methods to the top like how Javascript reorders stuff. In C it will, if you try to use -ansi flag will throw a huge error right at compile because the method calls in main cannot be found/referenced before declaration of the function signature and the method body itself.

Really in a FizzBuzz test, they aren't looking for a OOP solution it is an algorithm question of how do you deal with looping and control flow. Another quick question you get in an interview is looping through a singly linked list, using a loop is what they want to see and how you deal with copy. Another one is writing a factorial algorithm that does tail recursion or fibonacci sequence showing dynamic programming.
biggrin.gif


Entry Point of a program

So to make it even better control on the Entry Point try this:
Code:

Code:
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()  # Just a newline
        sys.exit()

"""import statements would go here if any"""

"""isFizz calcuates if the integer n is divisble by 3"""
def isFizz(n):
    FizzList = []
    if (n % 3 == 0):
        FizzList.extend((True, 'Fizz'))
    else:
        FizzList.append(False)
    return (FizzList)

"""isBuzz calculates if the integer n is divisble by 5"""
def isBuzz(n):
    BuzzList = []
    if (n % 5 == 0):
        BuzzList.extend((True, 'Buzz'))
    else:
        BuzzList.append(False)
    return (BuzzList)

"""isFizzBuzz calculates if the integer n is divisble by 3 and 5"""
def isFizzBuzz(n, myFizzList, myBuzzList):
    myFizzList = isFizz(n)
    myBuzzList = isBuzz(n)
    if (myFizzList[0] == True and myBuzzList[0] == True):
        return (myFizzList[1] + myBuzzList[1])
    elif (myFizzList[0] == True and myBuzzList[0] == False):
        return (myFizzList[1])
    elif (myFizzList[0] == False and myBuzzList[0] == True):
        return (myBuzzList[1])
    else:
        return n

def main():
    for i in range(1, 101):
        try:
            print(isFizzBuzz(i, isFizz(i), isBuzz(i)))
        except ValueError:
            "Your fizz can no longer buzz!"
 
Quote:
Originally Posted by adramalech707 View Post

It just goes against certain languages with a strict entry point. But in the long run I believe the compiler is smart enough to reorganize the code and be able to float the methods to the top like how Javascript reorders stuff. In C it will, if you try to use -ansi flag will throw a huge error right at compile because the method calls in main cannot be found/referenced before declaration of the function signature and the method body itself.

Really in a FizzBuzz test, they aren't looking for a OOP solution it is an algorithm question of how do you deal with looping and control flow. Another quick question you get in an interview is looping through a singly linked list, using a loop is what they want to see and how you deal with copy. Another one is writing a factorial algorithm that does tail recursion or fibonacci sequence showing dynamic programming.
biggrin.gif


Entry Point of a program

So to make it even better control on the Entry Point try this:
Code:

Code:
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()  # Just a newline
        sys.exit()

"""import statements would go here if any"""

"""isFizz calcuates if the integer n is divisble by 3"""
def isFizz(n):
    FizzList = []
    if (n % 3 == 0):
        FizzList.extend((True, 'Fizz'))
    else:
        FizzList.append(False)
    return (FizzList)

"""isBuzz calculates if the integer n is divisble by 5"""
def isBuzz(n):
    BuzzList = []
    if (n % 5 == 0):
        BuzzList.extend((True, 'Buzz'))
    else:
        BuzzList.append(False)
    return (BuzzList)

"""isFizzBuzz calculates if the integer n is divisble by 3 and 5"""
def isFizzBuzz(n, myFizzList, myBuzzList):
    myFizzList = isFizz(n)
    myBuzzList = isBuzz(n)
    if (myFizzList[0] == True and myBuzzList[0] == True):
        return (myFizzList[1] + myBuzzList[1])
    elif (myFizzList[0] == True and myBuzzList[0] == False):
        return (myFizzList[1])
    elif (myFizzList[0] == False and myBuzzList[0] == True):
        return (myBuzzList[1])
    else:
        return n

def main():
    for i in range(1, 101):
        try:
            print(isFizzBuzz(i, isFizz(i), isBuzz(i)))
        except ValueError:
            "Your fizz can no longer buzz!"
That code won't run. The __name__ == __main__ MUST go at the bottom of the page.
 
1 - 20 of 23 Posts