r/ProgrammerHumor •

[deleted by user]

[deleted] — view deleted post

0 Upvotes

446 comments sorted by

128

u/zebishop Jan 16 '14

What is really brilliant here, aside of the naive (yet perfect) answer, is the ordering of the results in columns that highlights the pattern of this algorithm

0

u/[deleted] Jan 16 '14

[deleted] — view deleted comment

38

u/atrain728 Jan 16 '14

As someone that interviews, I'd like to say I'd give credit for cleverness, but I think I'd mostly see this as being a smartass.

I don't think it'd go well from there.

11

u/grimeMuted Jan 16 '14

I don't think smartasses like to do tedious things.

16

u/gimpwiz Jan 16 '14

Good. Let them automate the tedious tasks.

15

u/[deleted] Jan 16 '14

You mean like a program of some sort?

15

u/gimpwiz Jan 16 '14

Maybe even executed by some sort of very fast hardware.

10

u/[deleted] Jan 16 '14

Possibly organized into an array of words that translate to machine code but is easily readable?

15

u/gimpwiz Jan 16 '14

Sir, I do not believe such a thing is possible.

1

u/DrDalenQuaice Jan 24 '14

I'd hire a smartass. They can be useful

77

u/[deleted] Jan 16 '14

[removed] — view removed comment

36

u/curtmack Jan 16 '14 edited Jan 16 '14

Actually, this is not too dissimilar from one of the most optimal FizzBuzz algorithms:

Create the following lookup list:
  [ "", "", "Fizz", "", "Buzz", "Fizz", "", "", "Fizz", "Buzz", "", "Fizz", "", "", "FizzBuzz" ]
For all numbers n from 1 to 100:
    Take the string in the lookup list at the index (n-1 mod 15), call it s
    If s is the empty string, print the number n
    Otherwise, print s
End for

Convert to the required language as needed. For bonus interviewer points, dynamically generate the lookup list (not hard).

Edit: Syntax error on line 2, near 'FizzBuzz'

45

u/jonnywoh Jan 17 '14

+/u/CompileBot python

a = [ "", "", "Fizz", "", "Buzz", "Fizz", "", "", "Fizz", "Buzz", "", "Fizz", "", "", "FizzBuzz" ]
for i in range(1, 101):
    s = a[(i-1) % 15]
    if len(s) == 0:
        print i
    else:
        print s

61

u/CompileBot Green security clearance Jan 17 '14

Output:

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

^source | ^info | ^git | ^report

33

u/aroymart Jan 17 '14

This is an awesome bot

21

u/Shamus03 Jan 17 '14

+/u/CompileBot python 3

print('I am an awesome bot.')
→ More replies (62)
→ More replies (3)

5

u/Tmmrn Jan 17 '14

Why empty strings, isn't None easier to recognize as falsey?

+/u/CompileBot python

a = [ None, None, "Fizz", None, "Buzz", "Fizz", None, None, "Fizz", "Buzz", None, "Fizz", None, None, "FizzBuzz" ]
for i in range(1, 101):
    s = a[(i-1) % 15]
    print (s if s else i)

4

u/kqr Jan 17 '14

Because heterogeneous lists are not beautiful. And the empty string is falseish anyway, so your code would work with empty strings as well.

(By the way, s if s else i is just s or i.)

→ More replies (2)
→ More replies (3)

10

u/shanoxilt Jan 16 '14

We could use you on /r/28thworldproblems, a realm where ants talk in pseudo-code.

2

u/mgdmw Jan 17 '14

My mind is blown. Why does that subreddit exist?

→ More replies (1)
→ More replies (2)

2

u/Ph0X Jan 17 '14

It's from 1 to 100 (a constant), so it'll be really hard to have a finite yet non-O(1) algorithm for fizzbuzz. I'm sure someone will manage though.

EDIT: Well, technically, it's impossible, because O(1) refers to the time complexity with respect to the input, but fizzbuzz doesn't have an input, so that doesn't work.

2

u/FoeHammer99099 Jan 17 '14

The problem does have an input, the range of numbers that the results will be printed for. It's just that everyone only asks for a specific example of the FizzBuzz problem.

→ More replies (4)

1

u/atrain728 Jan 16 '14

This would get a is this guy serious look.

149

u/novagenesis Jan 16 '14

What does an employer expect when they ask the FizzBuzz question in a way only completely unambiguous to someone who knows the FizzBuzz question?

Why not just say "hey, can you do fizzbuzz?"

132

u/Innominate8 Jan 16 '14

For someone who has no idea what fizzbuzz is, what this person did is not an unreasonable interpretation of the instructions. Technical interviews are often full of arbitrary seemingly unrelated questions brought on by interviewers who think they're being clever so it's hard to figure out what they actually want out of it.

It only looks stupid when you know what fizzbuzz is and fill the unwritten instructions in mentally. So in the end it's pretty much asking "Do you know what fizzbuzz is well enough to fill in the missing instructions?"

54

u/TheRingshifter Jan 16 '14

To be completely fair, this interpretation is the only reasonable interpretation of what the question asks... if you take it literally. If you write out some code on a piece of paper that code is never going to actually "print" anything. But writing the numbers out is printing them... the question should really just be worded:

"Write pseudocode (or java or whatever) which will ... [etc]"

It took me a good minute or two to figure out what he did wrong and I'm pretty sure I've heard of fizzbuzz at least in passing...

24

u/Xaquseg Jan 16 '14

Technically what's written there is already a form of pseudocode, I think the person writing the answer interpreted the question as "evaluate this pseudocode".

38

u/[deleted] Jan 16 '14

Yeah, honestly I had to come in to the comments to see why this was funny...I mean, I'm just learning to program and have obviously never had an interview, but were I presented with that piece of paper I wouldn't know what to do other than what the person in the picture did.

20

u/danillonunes Jan 17 '14

FizzBuzz is a common question asked by interviewers. The task is really easy and can be solved by good programmers in minutes, the purpose is only to filter out people who don’t have any clue of what they’re doing.

Generally, the task is: Write a program that prints the result shown in the image, but the instructions didn’t mention the "program" part, so OP read it literally and just wrote the expected result, as asked.

23

u/Innominate8 Jan 17 '14

The task is really easy and can be solved by good programmers in minutes

The task is trivial and can be solved by bad programmers in minutes, it's literally intended to quickly exclude people who have no ability to program at all.

Amusingly, when presented to programmers in a web forum, a significant number of them take it as a challenge and quickly post implementations of it. More amusingly many of them are invariably wrong.

6

u/mirhagk Jan 17 '14

The task is trivial and can be solved by bad programmers in minutes

It's surprising just how many university graduates fail this. This problem has basically made me lose all faith in our education system.

7

u/[deleted] Jan 17 '14

Wait, there are people with degrees who can't write a few else-if statements? What the fuck did they do to get through college?

3

u/kqr Jan 17 '14

They worked in groups, they copied code from StackOverflow, they spent hours debugging simple errors, they learned programming to pass the course and then forgot about it immediately after.

→ More replies (8)

3

u/takatori Jan 17 '14

ITT: hundreds of people trying to be clever by posting awkward solutions that they think are amusing and original.

2

u/weggles Jan 17 '14

I was worried for a second reading this because this looks stupid easy. "But if it's an interview question it can't be that simple. Oh god I'm missing something. " etc. As I slowly doubt all my programming skills.

1

u/[deleted] Jan 23 '14

I'm going to school for computer science and I aim to graduate at the end of 2015. Never interviewed for a programming job before.

I would be scared if graduates could not solve this problem.

9

u/acfman17 Jan 17 '14

Python is pretty common for beginners, here's how to do it in that:

#Go from 0 to 100
for i in range(1, 101):
#Print Fizz if divisible by 3, print Buzz if divisible by 5, print the number if not divisible by either
  print 'Fizz'*(not(i%3))+'Buzz'*(not(i%5)) or i

22

u/[deleted] Jan 17 '14

That's a bit obtuse for beginners. I'd go with the if i%3 == 0: print('fizz'), etc. solution.

3

u/acfman17 Jan 17 '14

Ah true, here's that solution if anybody wants it:

#Go from 0 to 100
for n in range(1,101):
    #Create an empty string to store output
    output = ""
    #Add Fizz to the output if number is divisible by 3    
    if not (n%3):
        output += "Fizz"
    #Add Buzz to the output if number is divisible by 3    
    if not (n%5):
        output += "Buzz"
    #Print output if input was divisible by 3 or 5 otherwise print input
    print output or str(n)

23

u/djimbob Jan 17 '14 edited Jan 17 '14

This is extremely unpythonic and an ugly hack. It's ok for a quick script never to be used by anyone other than you, but bad code to demonstrate for a software engineering interview. From import this:

Simple is better than complex.
Sparse is better than dense.
Readability counts.

First, comments that lie are much worse than no comments at all. Your first comment lies; range(1,101) goes from 1 to 100 inclusive, not 0. Code that you don't need to comment is much cleaner than code that you need to comment. For a trivial piece of logic like this, don't mess it up by relying on python casting i%3 to a bool, applying not to it, and casting it back to an int type for string multiplication, as well as relying on or precedence being lower than string concatenation/multiplication.

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

Not counting indentation/whitespace this clear obvious solution is 130 characters. Yours is 200 characters due to the terse code necessitating comments.

8

u/crazymuffin Jan 17 '14 edited Jan 17 '14

I like Java more.. example code, I bet there's thousand times better and simpler solution, but I'm, too a mere apprentice.

for (int i = 1;i<=100;i++) {
   boolean printed = false;
   if (i%3==0) {
      System.out.print("Fizz");
      printed = true;
   }
   if (i%5==0) {
      System.out.print("Buzz");
      printed = true;
   }
   if (!printed) {
      System.out.print(i);
   }
   System.out.print("\n");
}    

3

u/jdb12 Jan 17 '14

Dont do printlns. That way you can do the fizzbuzz automatically. Just have it do a blank println or print("\n") at the end of the function.

2

u/crazymuffin Jan 17 '14

Fixed. Drinking + coding = not a good idea :D

→ More replies (2)
→ More replies (4)

15

u/BananaPotion Jan 17 '14

2hacky4me

1

u/PZ-01 Jan 17 '14
for i in range(1,101):print"FizzBuzz"[i*i%3*4:8--i**4%5]or i

If you can do it in python once, you can make a one liner out of it the second time.

→ More replies (1)

0

u/[deleted] Jan 17 '14

[deleted] — view deleted comment

2

u/[deleted] Jan 17 '14

I've never been able to properly decide if python's typing is a great idea or an awful one.

When I'm not trying very hard, it's the perfect language; I give the computer simple, easy, logical instructions broken down to small chunks, and it does what I expect.

When I'm really on fire and in tune with the interpreter, I can give make the problem simplify into tiny, condensed snippets of code and basically solve itself.

When I think I'm on fire, but I'm really not paying attention, I end up doing something stupid and multiplying pointers all over the place and breaking everything. Those are the days that I curse under my breath and wish duck typing to be banished to wander the lost regions of the Sahara for a thousand years.

0

u/Ph0X Jan 17 '14

Eh, while I agree that it was ambiguous, I think that makes the test even better. I would never write down 100 things on a paper like that. Even if that's what it asked for, I'd still write it in code form.

I think it filters out people who think with code from people who just do it the long way. For example, I just wrote a script yesterday to automatically archive my music collection. I could've manually done that every time I grabbed a new album, but instead, I took a few hours to write something that will save me a lot of time in the long run.

That's something most people wouldn't know how to or wouldn't even think of doing. Here, this question is ambiguous, and you could either think of doing it with code, or manually, and that shows exactly what kind of thinker you are.

6

u/wonkifier Jan 17 '14

Funny thing is I value communication.

What I ideally want is someone who would see this, recognize what I probably meant, and confirm it with me before wasting time.

I would appreciate writing all of the numbers out as the picture showed as well, since they did what I actually asked for... just not as much.

If you decided to just give me code, I wouldn't automatically fault you for it, but I'd be setting up a question to find out why you answered it that way. And I really hope you're smart enough to say something about understanding the intent of the question. If you don't point out that there was some ambiguity there, then I probably don't want you around.

Being able to spot sources of risk or ambiguity is an extremely valuable skill.

→ More replies (1)

1

u/PrincessFred Jan 17 '14

My argument would be that if they knew they were interviewing for a programming position they should have been able to sort out the context.

2

u/Innominate8 Jan 17 '14

Why? With all of the 'clever' questions common in these interviews, it could just as easily be a test about following instructions or communication.

1

u/charc0al Jan 17 '14

If you want to be a software developer you better be able to fill in missing, incomplete, and nonsensical instructions.

1

u/Innominate8 Jan 17 '14

I would argue the exact opposite, as a software developer following the specification precisely is okay, asking for clarification or modification is better. Filling in the holes with uneducated assumptions is the worst thing you can do. Keep in mind, we're talking about the case where the interviewee has no idea what fizzbuzz is.

17

u/JBlitzen Jan 16 '14

Even knowing it, I see those instructions as deliberate, as if they want what he wrote.

That or they outsourced the instructions to some $1/hr elance dude in India.

If I were that company's owner, I'd be way more disappointed by the interviewer than the candidate.

2

u/ZarinaShenanigans Jan 17 '14

Or more accurately, "do you know how to apply modular arithmetic to a simple programming problem?"

1

u/jo_bo_bo Jan 16 '14

This is exactly how I would have answered it.

→ More replies (6)

48

u/matterball Jan 16 '14

None of these answers are going to make it in the Real World. Here's a reusable enterprise quality solution for this problem: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition

10

u/robotmayo Jan 17 '14

Oh god the packages just never end.

7

u/jonnywoh Jan 17 '14

Now port the code to PHP line by line

1

u/canhazadhd Jan 17 '14

Dear god...

204

u/paranoid_twitch Jan 16 '14

This would be a whole lot funnier to me if we hadn't had like 30 people come though interviews like this. The number of people who apply for development jobs with no programming knowledge blows me away.

15

u/TheRingshifter Jan 16 '14

If it really bothers you so much why not just re-write the question so it's not ambiguous? To me, this shows nothing of a lack of programming knowledge. If it were not ambiguously worded, someone wouldn't even have to know what "fizzbuzz" is to work this out. It's really easy... just put "write code such that" in front of it...

→ More replies (8)

4

u/[deleted] Jan 16 '14

How do they get interviews though? Don't most employers want a Github link, experience, a relevant degree, or anything indicating that the applicant is familiar with what they're applying for?

4

u/paranoid_twitch Jan 16 '14

Donno, HR just hands me a stack and asks me to interview. I wish I had more insight to give you because that's probably the problem.

4

u/[deleted] Jan 16 '14

I withdraw my previous statement. I just remembered that during an interview for an internship I just had, they mentioned I was the only applicant to include a Github link.

Why though? Isn't it in everyone's interest to get to see the code?

5

u/paranoid_twitch Jan 16 '14

Sure, but personally I've found that personality is the biggest thing to interview for. Soft skills in addition to your technical skills. You can get the best programmer in the world and still be really hard to work with. Technical deficiencies are easy to solve, personality issues not so much.

4

u/[deleted] Jan 16 '14

Obviously, but isn't it a waste of resources to see if people are sociable and easy to work with and then find out if they're even a fitting candidate for the job, as opposed to doing it the other way around?

→ More replies (3)

4

u/jrk- Jan 16 '14

It would be fun if you could write that thing in asm. Maybe I should refresh my memory a bit (not enough memory in brain, only 640kb or so..)

6

u/Blecki Jan 16 '14

Yeah? You get tons of these people in interviews, and I, who have an extensive github history proving how capable I am, don't even get the interview...

1

u/ILoveHate Jan 17 '14

And here I was, with a CS degree and full knowledge of how to program most things, or at least get a good idea of how to do it within 5 minutes of being assigned the problem, and I was shit scared of applying for fear of disappointing people. And I never did get the first job I applied for because I felt I couldn't code a quick sort from scratch, because you know, (at least the one I saw) it was 30-40 lines of code in a single recursive function. 5-10 is hard enough, so sorry for doubting myself on 30-40 .

1

u/paranoid_twitch Jan 17 '14

I think you replied to the wrong thing?

0

u/FurbyTime Jan 17 '14

I am a full software engineer. Like, with a job title and everything. I'm not high enough in the company to actually have a say in hiring staff, but apparently, I've been one of the better candidates they've had; And I came in there not even knowing the same LANGUAGE as they wanted.

They're hiring other people now because they need more people (And someone more than "fresh out of college"), but it's outright horrible how bad some of these so called devs are.

→ More replies (2)

0

u/[deleted] Jan 16 '14

[deleted] — view deleted comment

96

u/didzisk Jan 16 '14

So, apparently the FizzBuzz programming interview task isn't common knowledge yet... After like what, 10 years?

OK, 7 years.

→ More replies (23)

9

u/paranoid_twitch Jan 16 '14

That's understandable, I'm sure the interviewer had a good chuckle too. Hope it went well after that!

→ More replies (7)

0

u/[deleted] Jan 16 '14

[deleted] — view deleted comment

98

u/Lord_Naikon Jan 16 '14

Nope, you need to learn about % first :)

→ More replies (51)
→ More replies (1)

0

u/[deleted] Jan 16 '14

[deleted] — view deleted comment

29

u/paranoid_twitch Jan 16 '14

If they aren't in programming jobs that's fine. I know some really good network engineers that couldn't write a line code to save their lives. That's what we are here for.

→ More replies (8)

103

u/tohryu Jan 16 '14 edited Jan 17 '14

I had to come to the comments to understand why this was wrong and what it had to do with computing.

Nowhere on the page that I can see does it say to write an algorithm to do it, it literally says"do this". I would have done the same thing and thought it was the most pointless exercise ever.

26

u/digitalpencil Jan 16 '14

In all fairness, if it was a programming job and had I never heard of fizzbuzz, I would have assumed that they wanted pseudo-code simply from context and the use of the term 'print'.

Would have been better if they actually requested pseudo-code though as this is a literal interpretation and not technically incorrect.

13

u/Massless Jan 16 '14

Understandable, to a point, but you should probably read a hiring blog.

25

u/Talran Jan 16 '14

Oh? Good source for similarly vaguely worded interview questions?

I rather prefer the more direct approach.

11

u/Massless Jan 16 '14

Nah, not interview questions. Instead, a peek inside the heads of hiring managers so your job search can be more efficient. Fizz Buzz comes from the coding horror blog which tends to be informative and entertaining. I've found that there's rarely a direct approach when looking for a new position.

4

u/Talran Jan 16 '14

Ahhhh, yeah; most applicants are downright terrible.

We have a direct test at the start of our interview that asks you to pesudocode (on paper) a few simple database operations. 95% of applicants can't do anything even halfway suitable. For pesudocode. People with 4 and 6 year degrees in CS.

14

u/ActionScripter9109 my old code = timeless gems, theirs = legacy trash Jan 16 '14

I managed to get through a good 4-year CS program with no database experience. Probably would have bombed that question, and I'm a fine programmer.

6

u/wtf_apostrophe Jan 16 '14

Seems odd to omit databases from a CS course. They're pretty ubiquitous in industry..

9

u/ActionScripter9109 my old code = timeless gems, theirs = legacy trash Jan 16 '14

I agree. More than once I found myself sitting in interviews feeling like a dumbass, wondering how in hell it wasn't a required class.

→ More replies (7)
→ More replies (1)

3

u/Talran Jan 16 '14

Really depends, if you have the idea that you want data out of somewhere to somewhere else you'd probably be fine. As long as you 'get' the basics and are a decent person otherwise we don't mind teaching.

Heck, just knowing how databases work at all would put you ahead of the crowd. Not even in depth, but knowing what a table is, what data elements are, and such would be awesome. You'd be fucking stellar if you could tell us what an index, pointer or key is.

→ More replies (3)

2

u/FurbyTime Jan 17 '14

I'm fresh out of college at my current job; I'm outright horrified at some of the people they're interviewing. These are people that profess years of experience as well as a degree who can't explain simple concepts, who puzzle over simple problems, only to be unable to complete them.

I, meanwhile, walked in, still in college, not quite fresh on my high level programming since I was currently in the low level programming part of the course, not even remotely familiar with the language they used, and walked out with a job later that same day.

I've only lately come to realize that I was chosen not because of how good I am, but because of how outright horrible everyone else is.

2

u/Talran Jan 17 '14

It's something you see a lot in the field; generally, you don't hire long term because they know X language, you hire them because when you do, they'll pick up what you're codebase is and be able to work with it. You want sharp people who can adapt over people who can't think their way out of a paper sack but "theoretically" know how from working with said sack for 17 years.

2

u/Kinglink Jan 16 '14

If you're getting hired for a programming job I'd assume you (and I ) would write an algorithm...

But also this answer should get some points because it is valid... stupid but valid.

1

u/sophacles Jan 17 '14

Without context, sure. But there is nothing that says it wasn't page N of a multi problem excercise, with the first page saying something like: for each of the following pages, write a program that implements the instructions on the page. Or the interviewer could have handed the paper to the interviewee saying, implement these requirements.

17

u/ehmpsy_laffs Jan 16 '14

A project manager is born.

8

u/katyne Jan 16 '14

guise... you guise... monoids

no srsly

1

u/iopq Jan 17 '14

Holy shit, this is finally the correct FizzBuzz solution. I was annoyed how I couldn't come up with one that solves the problem in a maintainable way (since it's pattern match on all the cases at the same time + default case)

1

u/kqr Jan 17 '14

Wow, that is neat. It captures the whole "build-a-string-and-if-there's-no-string-make-the-number-a-string" pattern so well, in like two lines for a standard fizzbuzz instead of the 8 or whatever it is in Python.

7

u/thomplinds Jan 16 '14

had to answer this question for my first ever professional job, this is extremely entertaining

7

u/rohanivey Jan 17 '14

My friend looked over my shoulder at this, "What language did they want it in?"

"I'm guessing not English."

6

u/[deleted] Jan 21 '14

Is this seriously an interview question? I'm a 16 year old with little/no Java experience and this looks way too easy. For loop, if/else if/else statement, modulo operator, done.

8

u/tworing Jan 21 '14

This sort of question is routinely used during interviews as a first question because when you have an open programmer position you get a staggering number of applicants who do not actually know how to program. So by asking a question like this and immediately disqualifying anyone who can't write a reasonable solution to it within ~5 minutes, you save a ton of time by not having to actually interview people who had no business applying in the first place.

2

u/[deleted] Jan 21 '14

OK, makes sense! Thanks!

So what you're telling me is, I'm ahead of the majority of programmer applicants simply by knowing basic Java?

→ More replies (4)

24

u/djimbob Jan 16 '14

While their answer perfectly follows the vague instructions, it shows the candidate failed this part of the interview.

Why? Because before blindly doing the task, they didn't think about the larger context (in a programming interview, no one cares about your ability to act out non-code instructions), what was more likely to have been meant (even if it wasn't specifically specified), and didn't ask any clarifying questions. In the real world, instructions will be vague more often then not.

(Granted, you can fail one part of an interview and potentially still get a job offer, especially if you do very well on other aspects).

1

u/kqr Jan 16 '14

I don't think anyone disputes they failed this part of the interview.

15

u/[deleted] Jan 16 '14

I do. The question was a train wreck. Being able to answer that would be indicative of how many interviews someone has had, nothing more.

2

u/kqr Jan 16 '14

We know very little of the question. I assume there was some context around the situation that made it clear they were given a program specification. If they were just walking down the street and without a word got handed that paper as we see it, I would agree.

2

u/shhalahr Jan 24 '14

I assume there was some context around the situation that made it clear they were given a program specification.

On what basis do you make this assumption? I've had a few programming interviews that have been mostly brain-teaser and logic problem type questions and very few actual programming questions. So even the fact that this was for a programming job isn't enough context for such an assumption.

2

u/djimbob Jan 16 '14

Well, it depends the context. If you are being hired for a job that's not purely programming, and say the previous page had brain teasers, math problems or problems related to the skills they wanted, then yeah I could almost understand someone doing this; thinking it was an attention to detail task or something.

By the way, I think FizzBuzz is a reasonable question to weed out completely unqualified candidates that somehow made it too far. A lot of people get good at talking the talk or buttering up their resume, but can't code for their life.

1

u/djimbob Jan 16 '14

I feel the title and a few comments in the thread place some blame on the poor instructions and not the bulk of the blame on the interviewee.

Pointing out the interviewer didn't ask for you to write source code and literally following their instructions to the letter isn't going to gain you points.

1

u/jasonthe Jan 16 '14

It would depend on the rest of the interview. The entire point of FizzBuzz is to weed out people who can't even do the most basic programming tasks.

Though, looking at OP's comments, it sounds like the guy actually didn't do it as a joke and was just terrible. So, yeah, fail.

2

u/djimbob Jan 16 '14

It would depend on the rest of the interview.

Sure. If the interviewee then said something in a friendly casual manner like this is the weirdest task I've seen, did I miss the second part or something, and then quickly churned out a real version of FizzBuzz, it would be fine in my book, if they were otherwise a great candidate.

But it could also go the other way, if they got argumentative about it and seemed like that overly literal guy that no one wants to work with, then it could be a huge negative even if the rest of the interview was aced.

3

u/danillonunes Jan 17 '14

Overly literal guy here.

The worst part of this question is not the “He never asked me to write a program”, is, instead, the fact that he just copied this from somewhere on the internet and didn’t paid any attention to detail, while he expects me to do so.

3

u/FeepingCreature Jan 17 '14

Though, looking at OP's comments, it sounds like the guy actually didn't do it as a joke and was just terrible.

No, you're terrible!

Looking at OP's comments it's fairly obvious the guy is in fact perfectly capable of writing a FizzBuzz function and just made a silly error under pressure. If this is the sort of thing that causes you to pass over a candidate, you're needlessly donating part of your candidate pool to your competition.

→ More replies (2)

1

u/kqr Jan 16 '14

I think the title is joking and I can't speak for the comment author. If there was any sort of ambiguity, I would either ask if possible or just do both. Writing a fizzbuzz doesn't exactly take long anyway – especially compared to manually writing down the output.

I have no idea why anyone would think it's a good idea to just manually reproduce the output. It's a very dumb exercise and doesn't accomplish a lot.

9

u/quixotidian Jan 16 '14

Candidates are nervous and make dopey mistakes left and right.

If you're in the room you can intervene and prevent this kind of thing from losing too much time. If you're asleep at the wheel you aren't giving the candidate a chance to show their potential. Putting a candidate in a room with a simple problem (programming or otherwise) and then leaving before they have a chance to ask questions or start working is a very unproductive interviewing technique.

What's more is that the time it takes to write all that out is about 3 times as long as it'd take to write out a procedure that does fizzbuzz. It's a big enough difference that -- unless you're getting them water from the well in the next town over -- I would say it is also rude to leave a candidate for so long with so little to do but stew in interview nerves.

2

u/ActionScripter9109 my old code = timeless gems, theirs = legacy trash Jan 16 '14

Yes, the title is intended to be humorous, not literal. As for why he thought it was a good idea... I don't know. Judging by his other comments on Facebook, it was just a fluke moment of stupidity. He figured it out right after finishing.

1

u/shamas8 Jan 17 '14

What they did show is that they're willing to do mindless terrible tasks. I'd make him the janitor.

4

u/Kazinsal Jan 16 '14

My favourite way to do FizzBuzz involves nesting ternary operators.

A lot of people don't even think it's real code.

2

u/[deleted] Jan 17 '14

[removed] — view removed comment

1

u/Kazinsal Jan 17 '14

Damn. It's even a one-liner (two if you include my forto(var,first,last) macro).

Great LAN party trick though.

4

u/martinmine Jan 17 '14
for (int i = 1; i <= 100; i++)
{
	if (i % 3 == 0 && i % 5 == 0) print("FizzBuzz");
	else if (i % 3 == 0)          print("Fizz");
	else if (i % 5 == 0)          print("Buzz");
	else print(i);
}

1

u/nicholas818 Jan 20 '14 edited Apr 06 '14

+/u/CompileBot C

#include <stdio.h>

int main(void)
{
    for (int i = 1; i <= 100; i++)
    {
        if (i % 3 == 0 && i % 5 == 0) print("FizzBuzz");
        else if (i % 3 == 0)          print("Fizz");
        else if (i % 5 == 0)          print("Buzz");
        else print(i);
    }
    return 0;
}

7

u/[deleted] Jan 16 '14

Programming Student early in academic career who has never seen this test or heard of it. Am I being stupid to think just written else if in between the lines of instructions isn't sufficient enough? I assume because he didn't write code the tester gave him free will to write what he thought answer was and wouldn't it of just been easier or ok to show pseudo?

2

u/ActionScripter9109 my old code = timeless gems, theirs = legacy trash Jan 16 '14

Writing "else if" between the lines would not work... in this order. Consider the case where the number is 45. The first test would evaluate to true and it would print "Fizz", yet it should have printed "FizzBuzz".

The proper else-if based approach would be to test the 3+5 case first, then hit 3 and 5 separately with else-ifs.

Another strategy is to check 3 then 5 with if statements and not worry about 3+5. If a number is divisible by both, "FizzBuzz" gets printed since they both triggered. The issue there, of course, is that you have to put the newline at the end of the loop block, not in the print statements.

I had to complete this question a couple times in my interviews fresh out of university, so I've given it a fair bit of thought.

4

u/[deleted] Jan 16 '14

After reading your explanation then rereading problem I completely see where I went wrong. Thank you for explanation and even showing two separate ways.

2

u/ActionScripter9109 my old code = timeless gems, theirs = legacy trash Jan 16 '14

No problem. Now if you see it in an interview, you'll be ready!

10

u/KBKarma Jan 16 '14

I decided to see whether I could still do this. After a slight issue with having the mod 3 catch before the mod 3 && mod 5, I made this in Python really quickly. I've never done FizzBuzz in Python.

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

33

u/Kautiontape Jan 16 '14

You could make it a little more streamlined, by taking advantage of "FizzBuzz" being the same as "Fizz" + "Buzz"

for num in range(1, 101):
    p = ''
    if num % 3 == 0:
        p += "Fizz"
    if num % 5 == 0:
        p += "Buzz"
    print p or num

It's a little simpler, and more Pythonic

15

u/mcvoid1 Jan 16 '14 edited Jan 16 '14

Here's my $0.019999999...

(->> (range 1 101)  ; start at 1? Bunch of savages in this town...
     (map (fn [x]
       (cond (zero? (mod x 15)) "FizzBuzz"
             (zero? (mod x 3)) "Fizz"
             (zero? (mod x 5)) "Buzz"
             :else x)))
     (map println))

7

u/katyne Jan 16 '14

i might be getting old but in my day kids got smacked for being smartasses.

...unless you're even older and are being serious. In that case, with all due respect sir.

1

u/mcvoid1 Jan 16 '14

Well it's not pythonic but it's a serious Clojure solution. I like that you can see the flow from data to processing to output and how they link together.

1

u/[deleted] Jan 16 '14

Is this Clojure?

2

u/mcvoid1 Jan 16 '14

Yep. The ->> macro basically makes it the same as saying

(map println (map  (fn [x]
   (cond (zero? (mod x 15)) "FizzBuzz"
         (zero? (mod x 3)) "Fizz"
         (zero? (mod x 5)) "Buzz"
         :else x)))
   (range 1 101)))

Which is very similar to other types of lisp.

4

u/kqr Jan 16 '14
print p or num

This clever trick doesn't look very Pythonic to me. Do you have links to precedents or something?

3

u/Kautiontape Jan 16 '14

I tried finding you a good authoritative source using it (such as PEP 8), but haven't been able to find one. Otherwise, The Zen of Python encourages flat coding over nested coding, and in general, it is good Python tradition to avoid being needlessly superfluous if it makes sense to condense code. This obviously fits the bill, since it saves you an if/else statement in favor of a simple Boolean statement. I could dig around and see if there's any trusted Python code that does this if I had time.

At the very least, it's existed on [StackOverflow for years] (http://stackoverflow.com/a/1338532/586933) and a book tutorial.

5

u/kqr Jan 16 '14 edited Jan 16 '14

The more I look at it, the more I feel like accepting it as okay style, but it still looks weird to me. It makes so many assumptions about truthish values and short-circuiting behaviour and the return value of boolean operators so on. I mean, you need the empty string to be falseish, you need or to short-circuit and you need or to return the value of the first truthish argument – otherwise the last one. Maybe I'm just not used to it.

Edit: I just asked a bunch of Python programming friends and they all instinctively said, "Go for the or expression!" but when they looked at it closer they started to question whether they even gave the same result. While they do give the same result, I think their doubt speaks for avoiding it in production code.

4

u/Kautiontape Jan 16 '14

I completely agree that it falls on all those assumptions. However, all of those assumptions are relatively guaranteed to be true.

Python explicitly declares empty sequences as False in the documentation. They would have to change the standard in a very major way to not support this anymore (and it's unlikely, since I don't believe there would be anything to gain).

Python also explicitly states in the docs that and and or both short-circuit. This is traditional behavior in modern languages, and extremely beneficial for both performance and logic reasons.

Finally, the docs explicitly state the x or y syntax as "if x is false, then y, else x" which fits in line with only returning y if x is equivalent to false (such as an empty string).

Basically, while it may initially look like a shifty hack, it's actually well defined behavior. It's not using any undocumented features, and it's not relying on implicit knowledge.

2

u/Nghteye Jan 16 '14

Being documented doesn't still make it good. Unless some tiny perfomance edge is really important, one should choose a way that is intuitive to understand. Less bugs, easier for others to modify.

→ More replies (1)
→ More replies (1)

1

u/edbluetooth Jan 16 '14

isn't join considered more pythonic these days?

1

u/Kautiontape Jan 16 '14

This is true, so it could be "even more Pythonic." But concatenating two well-defined strings, I felt it was just way too verbose for the purpose. More than 3 or 4 strings, or concatenating values that may not be strings, and I would definitely use a join.

1

u/KBKarma Jan 16 '14

Oh, that's very nice.

3

u/seiyria Jan 16 '14

This inspired me to make a horribly contrived version in JS:

function isFizz(i)      { return i%divisors.FIZZ === 0; }
function isBuzz(i)      { return i%divisors.BUZZ === 0; }
function isFizzBuzz(i)  { return isFizz(i) && isBuzz(i); }

var divisors = {
  FIZZ: 3,
  BUZZ: 5
};

var functionsAndResults = [
  { function: isFizzBuzz, msg: "FizzBuzz" },
  { function: isFizz, msg: "Fizz" },
  { function: isBuzz, msg: "Buzz" },
];

for(var i=1; i<=100; i++) {
  
  var calledFunction = false;
  
  for(var func=0; func<functionsAndResults.length; func++) {
    if(functionsAndResults[func].function(i)) {
      console.log(functionsAndResults[func].msg);
      calledFunction = true;
      break;
    }
  }
  
  if(!calledFunction)
    console.log(i);
}

Had I been doing more CoffeeScript at the time, this could be a lot more elegant. C'est la vie.

(See also: Enterprise Fizz Buzz)

1

u/thomplinds Jan 16 '14

the only time i've done it i did it in python, but that was almost 4 years ago and i can read what you've written, but unsure if i could have written it myself anymore :/

1

u/didzisk Jan 16 '14 edited Jan 16 '14

I misunderstood the question and tried doing this without division, but it grew convoluted really quickly (save all states and keep track of them)... and then I got bored. Happened several years ago, so I have never in my life completed FizzBuzz.

Edit: Forget it, now I have. And why?

1

u/glaslong Jan 16 '14

In case you haven't seen it before, you should check out /r/dailyprogrammer. They post a problem of roughly this difficulty every Monday. It's pretty fun and good practice.

→ More replies (1)

3

u/takatori Jan 17 '14

It's a trick question: they were checking to see if he would use cursive instead of printing.

8

u/Chemical_Scum Jan 16 '14

dick stuck in FizzBuzz?

2

u/[deleted] Jan 16 '14

They didn't specify a language, was i supposed to write it in pseudo code?

1

u/Sargeron Jan 16 '14

I assume they'd let you do it in any language you choose. The intent behind this (I assume) is to test your logical problem solving using code, rather than proficiency in any given language.

2

u/[deleted] Jan 16 '14

Ah, good to know. I'm in computer science in college so that will be important to know when me getting a job is relevent.

1

u/Sargeron Jan 17 '14

Keep in mind that this might vary from employer to employer though. Some will probably want to test proficiency in a given language, but personally I found that once you learn a language like Java you can pick up a lot of the mainstream languages pretty quickly. Granted some are pretty unforgiving (I'm looking at you C).

3

u/[deleted] Jan 17 '14

I made the horrible mistake of learning actionscript 2.0 when i was like 12, and now its stuck as my default brain mode. Its awful, but someday i'll fix it. I've promised myself this.

→ More replies (1)

2

u/[deleted] Jan 16 '14

I am so lost. What is this? It looks like they did it right to me.

2

u/Sargeron Jan 16 '14

While FizzBuzz originally was intended to be done this way to teach children about division, it has been widely adopted by interviewers to test an applicant's programming skills. The asssumption made by the interviewer in OP's friend's situation is that the friend is aware of this and thus wouldn't need to be told that he needs to solve it using code.

Source

3

u/autowikibot Jan 17 '14

Here's the linked section Other uses from Wikipedia article Fizz buzz :


Fizz buzz has been used as an interview screening device for computer programmers. Creating a list of the first 100 Fizz buzz numbers is a trivial problem for any would-be computer programmer, so interviewers can easily sort out those with insufficient programming ability.

Adults may play Fizz buzz as a drinking game, where making a mistake leads to the player having to make a drinking-related forfeit.


about | /u/Sargeron can reply with 'delete'. Will also delete if comment's score is -1 or less. | To summon: wikibot, what is something?

1

u/[deleted] Jan 17 '14

This is so dumb. Nowhere on it does it say "solve using code". Somebody like me (who has never heard of this problem) would obviously just do it.

1

u/Sargeron Jan 17 '14

Agreed. The interviewer definitely made a mistake here in my opinion.

2

u/Xiver1972 Jan 17 '14

There are so many ways to answer this question...

for(int apple = 1; apple < 101; ++apple){
	switch(apple % 15){
		case 0:
			std::cout << "FizzBuzz";
			break;
		case 3:
		case 6:
		case 9:
		case 12:
			std::cout << "Fizz";
			break;
		case 5:
			std::cout << "Buzz";
			break;
		default:
			std::cout << apple;
			break;
	}
	std::cout << std::endl;
}

1

u/Xiver1972 Jan 17 '14
bool bMod3;
for(int apple = 1; apple < 101; ++apple){
	bMod3 = (apple % 3) == 0;
	if(bMod3){
		std::cout << "Fizz";
	}
	if((apple % 5) == 0){
		std::cout << "Buzz";
	}else if(!bMod3){
		std::cout << apple;
	}
	std::cout << std::endl;		
}	

4

u/thereddarren Jan 16 '14
		for (int i = 1; i < 101; i++)
		{
			bool divisibleBy3 = i % 3 == 0;
			bool divisibleBy5 = i % 5 == 0;

			if (divisibleBy3)
			{
				Console.Write("Fizz");
			}
			if (divisibleBy5)
			{
				Console.Write("Buzz");
			}
			else if (!divisibleBy3 && !divisibleBy5)
			{
				Console.Write(i);
			}
			Console.WriteLine("");//New Line
		}

And now I wait for smarter people to tell me what's wrong with it.

3

u/hbdgas Jan 16 '14 edited Jan 16 '14

Since the else if is following if (divisibleBy5), you don't really need to check !divisibleBy5 in it.

Edit: Also, since after making that change you'd then only be using divisibleBy5 once, you might as well just put the calculation directly into the if statement to free up that variable. But yours is really fine like it is for readability.

2

u/peclo Jan 16 '14

I like that version better. Easy to read, easy to extend.

1

u/[deleted] Jan 16 '14

braces

0

u/[deleted] Jan 16 '14

[deleted] — view deleted comment

1

u/thereddarren Jan 16 '14 edited Jan 16 '14

No, if I did that then I would never have FizzBuzz as a result.

EDIT: but since I did have an else there I could have said:

... if (divisibleBy5) { Console.Write("Buzz"); } else if (!divisibleBy3) { Console.Write(i); }

...

1

u/[deleted] Jan 16 '14

[removed] — view removed comment

20

u/thespacebaronmonkey Jan 16 '14

or not to verbose... that is the question

3

u/pirate_platypus Jan 16 '14

Since other people have tossed in their version, here's my submission for the silliest way to do it (Python 3)

[("FizzBuzz" if x % 15 == 0 else ("Buzz" if x % 5 == 0 else ("Fizz" if x % 3 == 0 else x))) for x in range(1, 101)]

3

u/VanFailin Jan 16 '14

There are a few python features that make it sillier. Try:

print('\n'.join((i % 3 == 0) * 'Fizz' + (i % 5 == 0) * 'Buzz' + (i % 3 != 0) * (i % 5 != 0) * str(i) for i in range(1, 101)))

2

u/hbwales Jan 17 '14

how about:

print('\n'.join((i % 3 == 0) * 'Fizz' + (i % 5 == 0) * 'Buzz' or str(i) for i in range(1, 101)))

2

u/thirdegree Violet security clearance Jan 17 '14

Things like this make me with it was valid python to use ! as a not operator :(

0

u/[deleted] Jan 16 '14

[deleted] — view deleted comment

1

u/pirate_platypus Jan 16 '14

Wow...

It reads like if Dean from Code Monkeys (great show) wrote code...

2

u/DemiReticent Jan 16 '14

I've never seen this problem and I could immediately tell that the intent was to have the person write code to do it. I mean, I would write a program anyway. Also, the use of the word 'print'. Am I the only one?

4

u/FeepingCreature Jan 17 '14

You're not in an interview situation. You're on Reddit.

2

u/cypr Jan 16 '14

You know those times during an interview when you get a problem that you can easily solve and therefor get relaxed and decide to initially break a related joke, try getting a smile from the interviewer, show some social skills and that you grasp not only the direct problem but also several different solutions and possible pitfalls.

Yeah, I don't think this is such a time.

1

u/Sakuya_Lv9 Jan 16 '14

I got this:

12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829FizzBuzz3132Fizz34BuzzFizz3738FizzBuzz41Fizz4344FizzBuzz4647Fizz49BuzzFizz5253FizzBuzz56Fizz5859FizzBuzz6162Fizz64BuzzFizz6768FizzBuzz71Fizz7374FizzBuzz7677Fizz79BuzzFizz8283FizzBuzz86Fizz8889FizzBuzz9192Fizz94BuzzFizz9798FizzBuzz

(hint: not println)

1

u/[deleted] Jan 16 '14

Q

1

u/Kinglink Jan 16 '14

This is clever. Actually there was a problem where someone wanted to know if all the numbers from 1 to some large number was Prime. the large number was under 100,000

So I wrote the program, and then left a second answer. I used the first program to generate the answers into a file, used that output as a array, (depending the number they pushed, I would output X of the array up to that number) and just posted that as my answer. Explaining the answer (Just looking up the first 100,000 values is faster than the sieve of eratosthenes.)

The question emphasized speed over algorithm, but I forgot what happened with the interview so I have no idea if that was the better answer.

1

u/kqr Jan 17 '14

Actually there was a problem where someone wanted to know if all the numbers from 1 to some large number was Prime.

putStrLn (if largeNumber > 3 then "No" else "Yes")

...going by the literal interpretation again.

1

u/Kinglink Jan 17 '14

On the sheet it actually said the number I forget it ( I want to say 100,000) but that's a good answer.

1

u/acfman17 Jan 17 '14

Rosetta Code has how to do it in over 180 languages. Everybody should be able to do this.

1

u/Rikkety Jan 17 '14

To be fair, this pseudo-code is by far the fastest implementation. It doesn't have the overhead of a loop, nor the expensive modulo and comparison operations.

If the question was to optimize for speed, this is exactly how I would do it (except maybe a "printf" or something similar preceding each line.

1

u/mm94 Jan 17 '14

am I missing something?

1

u/balkonkind Jan 17 '14

needs more design patterns:

var textMap = [
    { division: 3, text: 'Fizz' },
    { division: 5, text: 'Buzz' },
];

for (var number = 1; number <= 100; number++) {
    
    var isDividable = false;
    for (var i = 0; i < textMap.length; i++) {
        if (number % textMap[i].division == 0) {
            isDividable = true;
            break;
        }    
    }
    
    if (isDividable) {
        var consoleText = '';
        for (var i = 0; i < textMap.length; i++) {
            if (number % textMap[i].division == 0) {
                consoleText += textMap[i].text;
            }
        }
        console.log(consoleText);
    } else {
        console.log(number);   
    }

}

1

u/mcdileo Jan 18 '14 edited Jan 18 '14

Just because:

public void main()
{
    FizzTheBuzz(["Fizz", "Buzz", "FizzBuzz"], [3, 5, 15], 100);
}

/// <summary>
/// Takes a collection of strings and ints.
/// If any number below count is divisible by any of the conditions, it outputs
/// the matching text in the output array. The length of output and conditions
/// must be the same.
/// </summary>
/// <param name="outputs">What to say if there's a match</param>
/// <param name="conditions">On what numbers do you want to say an output?</param>
/// <param name="count">How high to you want to count</param>
public void FizzTheBuzz(string[] outputs, int[]conditions, int count)
{
    if (output.Length != conditions.Length)
    {
	    Console.WriteLine("The lengths of outputs and conditions don't match.");
	    return;
    }

    for (int i = 0; i < count; i++)
	    for (int i1 = 0; i1 < conditions.Length; i1++)
		    Console.WriteLine((i % conditions[i1] == 0) ? outputs[i1] : i);	
}

EDIT: what is wrong with me? Maybe it's just because it's Saturday and I don't want to do work.

1

u/nicholas818 Jan 20 '14 edited May 02 '14

+/u/CompileBot python

n = 1
while n<=100:
	fizz = n % 3 == 0
	buzz = n % 5 == 0
	if fizz and buzz:
		print "FizzBuzz"
	elif fizz:
		print "Fizz"
	elif buzz:
		print "Buzz"
	else:
		print n
	n += 1

1

u/CompileBot Green security clearance May 02 '14

Output:

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

^source | ^info | ^git | ^report

1

u/Coopsmoss Jan 16 '14

I've never heard of it, is this a serious programming interview question? Why am I'm unemployed, I'm practically a programming god comparatively.

0

u/[deleted] Jan 17 '14

FizzBuzz Program:

+/u/CompileBot C#

for(int i = 1; i <= 100; i++)
{
     if (i % 3 == 0) System.Console.WriteLine("Fizz");
     if (i % 5 == 0) System.Console.WriteLine("Buzz");
     if (i % 3 == 0 && i % 5 == 0) System.Console.WriteLine("FizzBuzz");
 }
 Console.ReadLine();

2

u/[deleted] Jan 19 '14

if (i % 3 == 0 && i % 5 == 0) System.Console.WriteLine("FizzBuzz");

Wouldn't

if (i %15 == 0) System.Console.WriteLine("FizzBuzz");

be better for this ?

1

u/[deleted] Jan 20 '14

The read out is the same thing and unless you're running this calculation one hundred thousand times per millisecond, I'm not sure it would make big difference other than the few characters you saved typing. In which case, it might also be better not to use "System.Console.Writeline()" 3 times but instead assign a string variable string s; [...] s = "Fizz" etc, [...]WriteLine(s); etc etc. for a net savings in typed characters.

0

u/biglebroski Feb 03 '14

+/u/CompileBot python

 a = 10
for a downto 0:
    print ("hello")
    a = a-1

0

u/PogOtter May 02 '14

Yay Python!

counter = 1 
while counter < 101:
    currentString = ""
    if counter%3 == 0:
        currentString = "Fizz"
    if counter%5 == 0:
        currentString += "Buzz"
    if currentString == "":
        print str(counter) +"\n"
    else:
        print currentString +"\n"
    counter += 1