I was incredulous when I read this observation from Reginald Braithwaite:
Like me, the author is having trouble with the fact that 199 out of 200 applicants for every programming job can’t write code at all. I repeat: they can't write any code whatsoever.
The author he's referring to is Imran, who is evidently turning away lots of programmers who can't write a simple program:
After a fair bit of trial and error I've discovered that people who struggle to code don't just struggle on big problems, or even smallish problems (i.e. write a implementation of a linked list). They struggle with tiny problems.So I set out to develop questions that can identify this kind of developer and came up with a class of questions I call "FizzBuzz Questions" named after a game children often play (or are made to play) in schools in the UK. An example of a Fizz-Buzz question is the following:
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".Most good programmers should be able to write out on paper a program which does this in a under a couple of minutes. Want to know something scary? The majority of comp sci graduates can't. I’ve also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution.
Dan Kegel had a similar experience hiring entry-level programmers:
A surprisingly large fraction of applicants, even those with masters' degrees and PhDs in computer science, fail during interviews when asked to carry out basic programming tasks. For example, I've personally interviewed graduates who can't answer "Write a loop that counts from 1 to 10" or "What's the number after F in hexadecimal?" Less trivially, I've interviewed many candidates who can't use recursion to solve a real problem. These are basic skills; anyone who lacks them probably hasn't done much programming.Speaking on behalf of software engineers who have to interview prospective new hires, I can safely say that we're tired of talking to candidates who can't program their way out of a paper bag. If you can successfully write a loop that goes from 1 to 10 in every language on your resume, can do simple arithmetic without a calculator, and can use recursion to solve a real problem, you're already ahead of the pack!
Between Reginald, Dan, and Imran, I'm starting to get a little worried. I'm more than willing to cut freshly minted software developers slack at the beginning of their career. Everybody has to start somewhere. But I am disturbed and appalled that any so-called programmer would apply for a job without being able to write the simplest of programs. That's a slap in the face to anyone who writes software for a living.
The vast divide between those who can program and those who cannot program is well known. I assumed anyone applying for a job as a programmer had already crossed this chasm. Apparently this is not a reasonable assumption to make. Apparently, FizzBuzz style screening is required to keep interviewers from wasting their time interviewing programmers who can't program.
Lest you think the FizzBuzz test is too easy-- and it is blindingly, intentionally easy-- a commenter to Imran's post notes its efficacy:
I’d hate interviewers to dismiss [the FizzBuzz] test as being too easy - in my experience it is genuinely astonishing how many candidates are incapable of the simplest programming tasks.
Maybe it's foolish to begin interviewing a programmer without looking at their code first. At Vertigo, we require a code sample before we even proceed to the phone interview stage. And our on-site interview includes a small coding exercise. Nothing difficult, mind you, just a basic exercise to go through the motions of building a small application in an hour or so. Although there have been one or two notable flame-outs, for the most part, this strategy has worked well for us. It lets us focus on actual software engineering in the interview without resorting to tedious puzzle questions.
It's a shame you have to do so much pre-screening to have the luxury of interviewing programmers who can actually program. It'd be funny if it wasn't so damn depressing. I'm no fan of certification, but it does make me wonder if Steve McConnell was on to something with all his talk of creating a true profession of software engineering.
Due to high volume, comments for this entry are now closed.
In case any readers don't know how to complete that test, here's a solution in VBScript. To try it - save the code into "c:\test.vbs" and run "cscript c:\test.vbs" from a command prompt.
Dim i
For i = 1 to 100
If (i Mod 3 = 0) And (i Mod 5 = 0) Then
WScript.Echo "FizzBuzz"
ElseIf (i Mod 3 = 0) Then
WScript.Echo "Fizz"
ElseIf (i Mod 5 = 0) Then
WScript.Echo "Buzz"
Else
Wscript.Echo i
End If
Next
Very very common, alas. I once interviewed a candidate for a VBA job (yes, you can stop booing for the peanut gallery) whom I asked to swap two variable contents without using a temp variable. It's the standard a=a+b, b=a-b, a=a-b problem. His answer? Well, I can't do it in VBA, but if you let me use Excel I can put the values in two cells and swap the cells' contents using a third cell.
We hired the guy who said, well, "if they're integers, then I'd do it by a=a|b, b=a^b, a=a^b. But I don't know how to do it if they're strings."
Toepopper on February 27, 2007 1:49 AMI've been making a decent living from programming for over ten years, and if I may say so, I write some damn good code.
However, I have never *once* used - or had call to use - recursion to solve a problem, since I learned about it at university. Does this make me a bad programmer? Or is it simply that people program in different ways for different problem spheres?
I simply can't believe that the other 199 people tested who can't write a simple for..loop have no career as some kind of programmer ahead of them.
Does that mean that every one of those people who do program but don't use (say) recursion is a bad programmer?
Or is it that you can't rely on any one testing method (like writing simple programs) to prove either way that the person can program effectivley or not?
The most obvious way to decide - for me - is to run through these tests, emply the person you like the best and then look at the code they've produced after a week. Then you'll know if they can do what you need.
The bottom line is, you can always learn to pass interview tests of any kind - that doesn't mean you can program or not.
AndyToo on February 27, 2007 2:00 AMI think the above solution is not elegant.
I think
If (i Mod 3 = 0) Then
WScript.Echo "Fizz"
End If
If (i Mod 5 = 0) Then
WScript.Echo "Buzz"
End If
because it covers the "both" case automatically. OK you have to care about line breaks which I don't know in VBS (never used that crap, thank goodness).
shenpen on February 27, 2007 2:05 AMI think the use of recursion probably depends on the particular field that you code in.
As a web developer I also have very little cause to use it. The only time I use it is when I need to search through the file system.
James on February 27, 2007 2:08 AMIsn't the code for that ..
int main() { ExitPaperBag(); return 0; }
I'm not sure ... copied it from somewhere :P
VibhavSharma on February 27, 2007 2:09 AMThere's a cynical voice in my head that says "because no-one has ever asked them to".
Where I work we spend a long time looking before we hire someone, because it's so hard to find them. We use a walk-through test that has a sequence of "questions" leading to a simple app and are willing to argue the toss (I was hired despite arguing that the test had significant flaws: "why would I do that? That's stupid because..." when they wanted me to code a solution that led to the next question).
I fear that any take-home or pre-interview component would lead to plagarism or "helped" solutions, so we make candidates perform in front of us.
That's got our ratio up to 3/4 good hires.
Moz on February 27, 2007 2:10 AMshenpen - Unfortunately that wouldn't be a valid solution (in VBScript) because WScript.echo adds a CRLF. In another language it might work though.
James on February 27, 2007 2:11 AMSorry, but if someone were to ask me how to swap two variables w/o a temp variable I'd ask them to give me a good reason why.
Not being able to answer that particular question certainly doesn't preclude someone from being a good programmer. That'd be like asking a C# programmer how to do modulo 16 using only a logical and. Why the hell would they need to know that, and how does that help you determine that they understand the ASP.Net framework, etc.?
Michael Reiland on February 27, 2007 2:18 AMshenpen: As you point out, your solution doesn't handle line breaks. It also doesn't print out the original number!
Mike Miller on February 27, 2007 2:18 AMshenpen, for shame. Read the spec again.
I don't think I've ever interviewed a programmer quite that bad, but I did have a conversation with a contractor I was replacing once: I'd introduced a class into the monster spreadsheet he'd been maintaining and he looked at it and remarked "I wish I knew how to do that". He was picking up about GBP400 a day (call it about $650 at that time) for this.
As I'm about to start looking for a programmer I shall be able to implement my long-cherished plan of asking candidates to submit a page or so of what they consider to be "good code". I don't mind if they wrote it or not, I want to see if we agree on the look of "goodness". If we get that far, I can find out if we agree on why it's good.
This is nasty but it's technically a one-liner:
1.upto(100) { |n| puts n % 3 == 0 ? n % 5 == 0 ? "fizzbuzz" : "buzz" : n % 5 == 0 ? "fizz" : n }
Mike Woodhouse on February 27, 2007 2:19 AMWOW! (and not the vista kind).
I can't believe there are people out there applying for jobs in software that cannot write a fizzbuzz program.
Gareth on February 27, 2007 2:23 AMIt's true that knowing how to do modulo 16 using AND doesn't relate to understanding ASP.Net.
On the other hand, do you want an ASP.Net technician, or someone who understands the theory behind it? Can you really call the candidate who only knows ASP.Net, but nothing about a basic logic a programmer (or a computer scientist, or a software engineer, or a coder), or is he just some guy who knows ASP.Net?
Mike Miller on February 27, 2007 2:23 AMJames: it's amusing to me that any reference to a programming problem-- in this case, FizzBuzz-- immediately prompts developers to feverishly begin posting solutions.
1) The whole point of the article is about WHY we have to ask people to write FizzBuzz. The mechanical part of writing and solving FizzBuzz is irrelevant.
2) Any programmer who cares enough to read programming blogs is already far beyond such a simple problem. It's the ones we can't rerach-- the programmers who don't read anything-- that we have to give the FizzBuzz test to.
But it's OK, I mean no offense. It's just funny. I know how software developers' minds work. :)
Jeff Atwood on February 27, 2007 2:36 AMMy point is that what you're asking for isn't "domain knowledge" strictly speaking. Using an XOR to swap two variables w/o a temp variable is only really useful when memory is expensive (embedded programming, et al). If you're not interviewing for an embedded programmer why are you worried about it?
Same with the modulo trick. The first time I ever encountered that I was writing a Perlin Noise Generator based off of someone else's work. Outside of routines that need to be highly optimized there's no reason for it.
Are you trying to hire an ASP.Net programmer or an embedded systems programmer? Granted, the XOR trick is pretty well known, but not knowing it off the top of your head says nothing about your abilities as a programmer (whereas the fizzbuzz example does).
No one can know everything. I would expect that type of attitude from a non-IT person, but not someone who is interviewing programmers.
Michael Reiland on February 27, 2007 2:44 AMHa ha! I see what you're saying Jeff.
I hope I didn't come across as feverish though. I sincerely thought that a solution may be of interest to someone who couldn't write one themselves.
Perhaps you have readers who aspire to be programmers but are still learning?
Perhaps a future Google search for "FizzBuzz" will bring back this page? (And the Googler might be after the solution).
Interestingly, the use of a technical test in interviews can actually work both ways. In my recent hunt for a new job I automatically turned down any vacancy where I was *not* given a technical test. My reasoning behind that is that I know *I* can program, but do I want to work with *other* programmers who haven't been tested?
The harder the test I was given, the more excited I was about the vacancy.
If anyone out there is looking for a new job I urge you to bear that in mind.
James on February 27, 2007 2:46 AMInstead of using recursion, it's often faster to use a Stack.
LKM on February 27, 2007 2:46 AMThere's always 'Survivor for Developers' for those who don't make the cut. http://techtalkblogs.com/blog/archive/2007/01/26/1837.aspx
At the end of each week, you vote the worst dev off the island.
Grant on February 27, 2007 2:50 AMIt's just performance anxiety.
Most people are terrified/stressed out during interviews.
Not "Can you X?" -
"Can you X whilst terrified?"
AndyToo wrote:
"However, I have never *once* used - or had call to use - recursion to solve a problem, since I learned about it at university. Does this make me a bad programmer? Or is it simply that people program in different ways for different problem spheres?"
i think you missed the point: if ou were explicitly tasked to write a algorithm using recursion, would you be able to do it ? would you be able to recognise the use of recursion while reading someone else code ? and most important, the one i struggled teaching to newly hired guys and which most people dont learn at school: do you understand the principles behind recursion ?
every good programmer knows there are plenty of ways to avoid recursion, but being able to avoid it implies that you know what recursion is.
and that is the point of such a question during an interview.
rien on February 27, 2007 3:25 AMDamnd thing took me three minutes to write in php. I am getting slower with old age ;-)
if ($x/3 == floor($x/3) ... and so on.
Kristoffer on February 27, 2007 3:42 AMI wonder why it is 199 out of 200 instead of more reasonable number like 99 out of 100? In any case I believe him. It is amazing how many people are paid to be programmers that struggle at the job and clearly should have been hired in the first place. When I used to teach college I noticed the same trend... a large number of CS student just really did not understand how to program. It was scary.
Tonetheman on February 27, 2007 3:45 AMHaving in the past been tortured by clueless candidates, I can believe the claim. Phone screening with simple as simple can be questions is amazingly (and disturbingly) effective. Where do these people come from?
While you may not have used recursion to solve a problem, if you know what it is and how to code something simple then that is enough, me thinks. There is a stunningly large population of people who describe themselves as 'professional software developers' who have not the faintest idea about recursion, bit masking, hexadecimal maths...or how to code a simple for loop that does something like FizzBuzz.
Over the years I've built up a loose theory on these "pretenders"--they are the people that know tinker and tweak and copy and paste and fidle and, when left alone for a while, some how manage to produce a bit of code that passes as productive.
Non technical people just cannot distinguish between them and us, and many times we technical people don't ask the right questions. What are we asking if not the FizzBuzz question? Surely it varies, but inevitably we are asking questions whose answers have nothing to do with problem solving and the mechanics of coding.
One of my FizzBuzz questions is, when a candidate has "SQL" on their CV, is to draw a simple table (Person: last, first, sex, DoB), populate it with four or five rows, and ask them to write some SQL that returns all the males, or everyone born after a given date. Simple enough problem, very real world, and relevant to someone working in 'web development'. Two out of three cannot do it! Ask for an insert or update? Four out of five, if not fewer!
Our profession is full of frauds and incompetent fools. And I feel safe saying that here because, if you are reading the comments on Jeff's blog, then you actually take an interest in both the nitty gritty of computers and programming...and the higher level fluff, like hiring. :)
>The majority of comp sci graduates can’t. I’ve also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution
Ofcourse we all know that being a elite programmer is all about how fast you can program, especially in a high-pressure situation.
Wow. Now that's sad. I don't call myself a programmer at all, and I could write a solution to this in Qbasic!
HaX80r on February 27, 2007 3:58 AMMost development is simple viewing and editing of data in forms.
Developers who can't write "fizzbuzz" can be productive in such an environment, especially if there is existing code they can copy and modify.
Most development is simple viewing and editing of data in forms.
Developers who can't write "fizzbuzz" can be productive in such an environment, especially if there is existing code they can copy and modify.
I suspect some of the people above complaining about the high pressure of having to write a ten line program including division may fall into this category. :-)
Me on February 27, 2007 4:05 AMif program does require recursion, then definitely everyone will use this.
shiva on February 27, 2007 4:12 AMfor (int i = 1; i < 101; i++)
{
if ((i % 3) == 0) Console.Write("Fizz");
if ((i % 5) == 0) Console.Write("Buzz");
Console.WriteLine();
}
"Most development is simple viewing and editing of data in forms.
Developers who can't write "fizzbuzz" can be productive in such an environment, especially if there is existing code they can copy and modify."
They'd also be an incredible liability. If fizzbuzz is beyond them, concepts such as memory/processor usage, security, stability, defensive programming, etc. are going to way out of their grasp. I've worked with someone like this; they _cost_ us time, because _everything_ they wrote had to be completely re-written by someone else. Unchecked inputs, error messages that consisted solely of dancing cats (seriously), SQL and HTML injection holes all over the place.
On writing a program to switch two variables without a temporary variable; while I had a hunch it involved bit operations of some kind, I certainly wouldn't know how to do it off hand.
On time taken to program; I'd probably spend several minutes just staring the FizzBuzz task, looking for some complexity I'd missed, so that's also something to take into account.
bool printint;
for (int i = 1; i <= 100; i++)
{
printint = true;
if (i % 3 == 0) { Console.Write("Fizz"); printint = false; }
if (i % 5 == 0) { Console.Write("Buzz"); printint = false; }
if (printint) Console.Write(i.ToString());
Console.WriteLine();
}
to LKM:
"Instead of using recursion, it's often faster to use a Stack"
do you understand how, in almost any language, recursion involves a stack ? you are just making the hidden part visible...
to shiva:
"if program does require recursion, then definitely everyone will use this."
agreed, but you are free to think a bit longer and see if you cannot avoid it. this is the difference between a good programmer and a smart programmer: the former knows how to solve the problem while the later invents new ways to solve the problem more efficiently.
to Fabian:
no, you forgot a part of the requirements. wroooong ! do it again !
to Jeff:
"it's amusing to me that any reference to a programming problem-- in this case, FizzBuzz-- immediately prompts developers to feverishly begin posting solutions."
it is also amusing how many of those solutions are wrong. so typical of our profession...
Back in '99, I was given a FizzBuzz task by a Microsoft recruiter to design a program that would take two inputs and determine if they were anagrams of each other. I began with a quick test of string length - if they didn't have the same number of characters then it was immediately rejected. He was very impressed that I would start with such a test. Seems most people would go through cycles and cycles regardless of the inputs.
To be honest as a recent grad and somone who is new to being a software developer I think if you are incompetant you shouldn't last long anyway.
In my first month at my new job I had to learn VB and C++ from scratch, two months later I was moved on to a project in C# using ASP.Net which I'd never used before. I've seen similar tests to the fizzbang questions, and they are useful.
My current employer gave me 3 hours to parse an XMl file and display it as a tree structure. I'd not spent much time playing with XML before but with after a quick google for a reference on the SAX api I was coding away. apparently half the candidates couldn't write anything and others didn't know how to use and IDE and insisted on using a text editor. which they screwed up.
Another couple of employers has written tests with small "write a code fragment to do this" and "spot the mistake in this code" questions. both were piss easy but there were some trick questions in there.
I think what should be tested especially for recent grads is not the knowledge per say, but the capacity to pick stuff up, I got my current Job becuase I took an API I had never used before and figured out how to use it. I'm by no means a pro, but I have the capacity to learn by myself, some people can't pick up new things unless they are spoon fed.
University is not an excercise in cramming your head full of knowledge it's an excercise in learning how to learn quickly and efficiently.
When you know the basics you can teach yourself a new language in a few hours, and depending on the complexity learn a new API in an hour to day. Many grads I find dont have that capacity, I did a masters with a bunch of people who came from different universities to me, and some of them just couldn't cope with having to fend for them selves.
Thats my two cents anyway. I think the fizbang questions help sift out the muck but the problem is more intrinsic and needs to be addressed at the level of academic institutions.
Omar on February 27, 2007 4:45 AMStu Thompson wrote, "There is a stunningly large population of people who describe themselves as 'professional software developers' who have not the faintest idea about recursion, bit masking, hexadecimal maths...or how to code a simple for loop that does something like FizzBuzz."
FizzBuzz, sure, any programmer should know how to write that. Bit masking though? That example just goes to show the wide range of expertise involved in programming, not all of which is required to be a successful or skilled programmer.
I don't think I've used bit masking (and I can't even remember what it is, exactly) since college. But Stu goes on to say talk about asking for SQL examples in interviews, and here not only would I be able to demonstrate inserts and updates - of course - but left joins, cross joins, multi-table deletes, whatever.
FizzBuzz is an acceptable test because it is non-domain specific, the same cannot be said for all other types of programming knowledge.
Ade on February 27, 2007 4:52 AMQuote: Granted, the XOR trick is pretty well known, but not knowing it off the top of your head says nothing about your abilities as a programmer (whereas the fizzbuzz example does).
True. However, someone who's never read enough professional literature (including programming blogs) to have seen this may either be:
a. very inexperienced OR
b. not interested in programming outside of coursework/their job.
I submit that such a person is never going to be a great programmer (although they may be, barely, adequate).
Mike Miller on February 27, 2007 4:54 AMCommon, unfortunately. The majority of CS grads can handle the trivial stuff like "FizzBuzz" (though a slight majority probably never really grokked recursion). But I've seen people hired at my last job who couldn't code.
in one case, the person did know a bit of syntax, but they had absolutely no debugging skills. This person didn't know the integrated debugger existed. They didn't even use simple debugging outputs to the console. No, their method of debugging was to randomly change stuff to see if it fixed their problem. Not surprisingly, that didn't work very well.
coderprof on February 27, 2007 4:56 AMFabian
Nice little snippet there. However, it doesnt fulfill the specification.
"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”."
You arent writing out i when its not %3 and/or %5
Close but no cigar.
Tatsky on February 27, 2007 5:00 AMI need a raise then, cause I actually write and ship a COTS version of the FizzBuzz application.
natron on February 27, 2007 5:01 AM"it is also amusing how many of those solutions are wrong. so typical of our profession...:
I noticed this as well. Makes one really start to question the worth of such statements as "if you're reading this blog, you're already much better than those *other* programmers".
Heres another solution
int i = 0;
for(i = 1; i <= 100; i++)
{
if(i % 15 == 0)
{
count << "FizzBuzz" << endl;
}
elseif(i % 5 == 0)
{
count << "Buzz" << endl;
}
elseif(i % 3 == 0)
{
count << "Fizz" << endl;
}
else
{
cout << i << endl;
}
}
My weapon of choice is Ruby
1.upto(100) do |i|
out = nil
out = out.to_s + 'Fizz' if i % 3 == 0
out = out.to_s + 'Buzz' if i % 5 == 0
puts out || i
end
And did you really think you could say "only 0.5% of programmers can write FizzBuzz" without people showing you how they do it? :P
Gareth on February 27, 2007 5:07 AMI remember at my first University course the teacher asking how many people never programmed before. Many hands were raised, and I felt bad for them for choosing a future profession without knowning what it actually was about. Then he asked how many people never touched a keyboard before. How shock was I to see at least 10 persons raise their hand, mostly women.
Martin Plante on February 27, 2007 5:10 AMI've witnessed the same, sad truth. It even inspired me to write my first blog entry on candidates attempts to code strcpy():
http://davidavraamides.net/blog/2005/05/07/strcpy/
I think the takeaway from this is that you are a fool if you are interviewing programmers and not requiring them to write some code.
Toepopper: swapping variables without a temp is more what I'd call tech trivia then useful knowledge. There really isn't a good use case for it anymore (its not even necessarily faster than using a temp since procs have so many registers these days). Besides, your solution of a=a+b, b=a-b, a=a-b fails in overflow cases. The candidate's XOR solution is more correct, but still unnecessary.
rien: you are right on regarding _understanding_ recursion. I agree that its frequently not necessary and often the less efficient solution, but being able to recognize that fact, and to read someone else's code, requires familiarity with the technique. And that's why I would consider it fair game in an interview.
David Avraamides on February 27, 2007 5:14 AM"we all know that being a elite programmer is all about how fast you can program, especially in a high-pressure situation." ....well, yes, if you've got an online application and somebody's just discovered a serious bug, sometimes that's exactly what it's about.
Recursion? I never used to use it either. Then I read the first chapter of Structure and Interpretation of Computer Programs, and some other stuff about writing compilers and interpreters. Now I use recursion all the time, coming up with all sorts of general, automated solutions for the sorts of tedious tasks I used to code out by hand.
Dennis on February 27, 2007 5:16 AMWhy can't they program? Because demand for good programmers has outstripped supply. Those of us who interview a lot of applicants (I've seen at least 50 the last year) know two things: most can't program, and those who can will be tough to get. And now it's been bad enough for long enough that many doing the hiring can't program either, so screening is often incompetent and these charlatans stand an excellent chance of getting hired anyway.
Testing is imperative, but some just seem reluctant to do it -- it seems so cold and mean.
Fizzbuzz looks like a good test. Here are two other standard questions, the first one broadly published and the second very general. Many "programmers" flop on one or both:
1. Draw four "cards", showing "A", "B", "2" and "3" respectively. Say that for each card there is a letter on one side and a number on the other side. I have a theory that if there is a vowel on one side of a card, then there will be an even number on the other side. Which cards do we need to turn over and examine the other side of to adequately test my theory?
2. What is a hash table, and when would you use one? Why might you prefer using a hash to using an unsorted array, or a sorted array? What tradeoffs are you making when you choose between a hash and a sorted array?
When the applicant doesn't know what a vowel is, or a hash table is, I know it's going to be a long day....
John Pirie on February 27, 2007 5:21 AMNeah... Jeff just wants us to fell all fuzzy and warm... No way I'm in like the top .5% of the programmers.
Anyway... I can do the FizzBuzz thingy... hi hi hi
for i in range(1,101): print {0:"FizzBuzz", 3:"Fizz", 6:"Fizz", 9:"Fizz", 12:"Fizz" , 5:"Buzz", 10:"Buzz"}.get(i%15, i)
@Ade: My point is that the many 'programmers' do not know *anything* about bit masking, *and* other core concepts. None. Zip-o. Nada. I did not mean to imply that all coders should have an encyclopaedic knowledge of all CS! :) Please don't obsess on my mention of bit masking alone.
Good for you on the SQL, but then again it is domain specific and I qualified it as such above. ('web development')
@rien: hehe, i agree on the urge to post code...it is funny...especially when it is incorrect
Hrmf!
I wouldn't hire any of you guys who sent in the Fizz/Bang program. You should have declared 5 and 3 constants, and used the constants in your code.
Besides, real programmers wouldn't program in VB, they'd use Perl. Now, if I can only get this page to work in my Lynx web browser.
David on February 27, 2007 5:24 AM"....well, yes, if you've got an online application and somebody's just discovered a serious bug, sometimes that's exactly what it's about."
Ugh, had one of those on Friday. Our caching system was spitting out the wrong data (by which I mean, the wrong user's data). Never showed up on the dev system because the caching system uses SoftReferences to allow the Java garbage collector to expire data from it, and the dev version never ran long enough for garbage collection to really be an issue. Important lesson about being _really_ sure about your compareTo() methods before using java.util.TreeMap.
Took us 40 minutes to locate, fix, and patch to live. Which is a little longer than usual, but locating the problem more or less came down to eliminating everything it couldn't be, then figuring out how it was the fault of what was left.
Geez guys - EVERY ONE of you who gave example code - EVERY ONE - hard coded the FIZZ and BUZZ conditions... And a LOT of you wrote code that will do the FIZZ, BUZZ and FIZZBUZZ but NOT print the integer...
kg2v on February 27, 2007 5:27 AMI just couldn't resist:
for(int i=0;i<100;printf(i%3==0?i%5==0?"Fizzbuzz":"FIZZ":i%5==0?"BUZZ":"%i",i++));
82 Characters
And yes, it's as dirty as it would ever get ... ;)
I've tested it with .NET 2.0 C++ and it works just fine ...
public class FizzBuzz
{
public static void main(String [] args)
{
int k;
for(int i=1; i<=100; i++)
{
k = 0;
if(i%3==0)
{
k = 1;
}
if(i%5==0)
{
k = k + 2;
}
switch(k)
{
case 1:
System.out.println("Fizz");
break;
case 2:
System.out.println("Buzz");
break;
case 3:
System.out.println("FizzBuzz");
break;
default:
System.out.println(i);
}
}
}
}
My biggest problem with solving simple programming problems tends to be the memorization involved with different languages, especially if I haven't used a particular language in a while. More often than not I'll go through my resume and remove (or limit mention of) languages that I used for only a short time or simply haven't used in a while.
For example, I feel quite competant with dealing with basic database issues, but without having touched a database in a few years I'd have to look up even the most basic sql statements, so I wouldn't claim to be a capable database programmer, though after a couple of weeks I could be at least a moderately good one.
Recursion is a similar problem with different languages. Some languages don't allow it at all, and others have very specific restrictions that make it a little harder to just jump in and say we'll just make this call here and make sure the conditions are in line to stop the whole mess from self-destructing.
In other words, I have a terrible memory, but I can still answer most of those questions with whatever language I've been using recently. I simply have to maintain my resume to avoid being asked questions that would send me to the books (or the web) to find an answer that should just spring to mind immediately.
Vizeroth on February 27, 2007 5:29 AMForgive me, but I can't resist...recursive fizzbuzz:
(Python)
def fizzbuzz(n):
if n:
if n % 15 == 0: return fizzbuzz(n-1) + 'fizzbuzz ';
elif n % 5 == 0: return fizzbuzz(n-1) + 'buzz ';
elif n % 3 == 0: return fizzbuzz(n-1) + 'fizz ';
else : return fizzbuzz(n-1) + ('%d ' % n)
return ''
>>> fizzbuzz(100)
DonS on February 27, 2007 5:30 AM"And did you really think you could say "only 0.5% of programmers can write FizzBuzz" without people showing you how they do it? :P"
Gareth: my guess is the ones who couldn't do it didn't bother to answer
Anecdotal "evidence" against this: When I started my first job after university (also, my first programming job), I could /maybe/ have answered FizzBuzz in Java. I'd programmed probably less than 1000 lines my whole life. Two months later I was improving my colleagues' code in a language I'd never used before. 2.5 years, some 36,000 lines of production code, and a good recommendation letter later, I'm stuck in a job market that only wants people with 5 years experience.
l0b0 on February 27, 2007 5:33 AM"Ofcourse we all know that being a elite programmer is all about how fast you can program, especially in a high-pressure situation."
So you think that, even in an interview, it's alright for an experienced professional to take 10-15 minutes to write FizzBuzz? That's more than one minute per line!
Eam on February 27, 2007 5:35 AM>do you understand how, in almost any language,
>recursion involves a stack ? you are just making
>the hidden part visible...
Do you understand that by using a local stack instead of the call stack, the computer needs to keep track of much less information and needs to do much less work building and tearing down the call stack? In most languages, using a stack instead of recursion speeds up your app tremendously.
Also, why the hostility? Did I somehow insult you? If so, I apologize, but I fail to see what exactly I did to you.
LKM on February 27, 2007 5:44 AMAny question can be made difficult. If asked an easy question, an interviewee knows they have to get it right and will become more nervous as time goes on. Over the course of three minutes, it can get *very* bad.
"Write a program that prints the numbers from 1 to 100."
Inclusive/exclusive? Are we in a language in which fencepost errors are likely?
"But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”."
On the same line or different lines?
"For numbers which are multiples of both three and five print “FizzBuzz”."
What about performance? The interviewee may be trying to remember how mod is implemented. And thinking about fence posts. And thinking about 3 cases of control flow. And "fizzbuzz". And working quickly. And acting calm. And why they're being asked this stupid question. Normally you do not deal with all of these things at the same time, but asking a simple question in a stressful environment in which the interviewee is getting ready to put 110% in to whatever you say will likely lead them in to trying to do so. There's only so much you can keep in your head, and even less when you're nervous. As you get more nervous (because the question is taking a long time), your nervousness will feed into itself.
Whenever I'm asked a question like that, I think the manager is clueless, both technically and in their ability to lead a team. Asking insightful questions about harder projects will reveal who did the work, and asking questions appropriate to the applicant will show you understand your team. This just shows you're a delusional asshole.
One company I know required applicants to do an almost code homework assignment before applying. A code sample or two as well as discussions of past projects should suffice and probably bring up good topics, as the subject will reveal what they're interested in. If you're a coder on the same project, ask for their solutions to problems you're having.
I stopped explicitly listing my technical skills recently and just put projects I have worked on - that also cut back on the bullshit questions people asked. When not given something distracting like that, interviewers have to think about better topics - and the interview may even become a fun conversation at that point.
anon on February 27, 2007 5:47 AMIt requires a huge deal of self-confidence to be as much effective during an interview as during your lazy sundays. Most of us will think twice before considering writing the *simplest* statement in front of an interview panel. I agree with most of this article - but it should really insist of the psychological factors (Of course, you could argue whether good programming abilities are dissociable or not from good social and communication abilities).
fabien on February 27, 2007 5:52 AMMike Reiland: when you wrote
"Not being able to answer that particular question certainly doesn't preclude someone from being a good programmer. That'd be like asking a C# programmer how to do modulo 16 using only a logical and. Why the hell would they need to know that, and how does that help you determine that they understand the ASP.Net framework, etc.?"
I think you missed the bloody point. There are plenty of people who "know the [fill in the blank] framework," but can't program worth a flying damn in a circus tent. I've worked with people who brought a Master's Degree in Computer Science to the table, but couldn't understand the concept of a state machine or even building flag values by accumulating bits. I showed a simple event-driven framework to one junior programmer and his response was "I wasn't taught that method." He didn't ever appear to grasp that there was more to the world than was taught in his Computer Science classes, and that we were allowed to actualy come up with and express ideas all on our own without a professor's approval. Needless to say, he didn't last long. (Actually, he was a little on the weird side; he kept coming to work after we fired him. That concept of being fired seemed beyond him as well.)
Check out http://worsethanfailure.com/Default.aspx for examples of people who "know the [f.i.t.b.] framework," but can't seem to express the simplest of concepts in code. It has little to do with hoop-jumping and clever tricks, and everything to do with getting the job done on a daily basis: some of these people come out of University with a degree and no idea at all how to code.
The company where I work has an extensive series of programming tests for potential new hires, including specific problems derived from the kind of coding we expect them to do on a daily basis. It's amazing how many people can't get through it. One applicant excused himself to go to the bathroom during the middle of the test, and never came back. It's not even a hard test.
For the record: wrote the FizzBuzz thing in under two minutes--right the first time. (In all fairness, though, I first started programming when I was 15, and that was 31 years ago. If I can't do FizzBuzz after that amount of time, I need to hang up the cape.)
mrprogguy on February 27, 2007 5:52 AMI think it's interesting to see how many people here are innately drawn to developing a solution to the problem, completely overlooking the original point (which was that many candidates wouldn't normally find themselves innately drawn to this).
I think this defines one key aspect of programmers who succeed, and those who simply maintain as they move forward: an inherent interest in/drive toward practicing (in the Dave Thomas "Code Kata" sense) their craft, vs. someone who simply views programming as a job to complete.
In any field, there are those who are passionate about what they do, and there are those who do it because they need something to do; it's just starting to catch up en masse with technology fields now. And it's not necessarily a bad thing: you always need people who would rather do repetitive tasks, and you always need people who would rather be tackling ambiguously-defined problems, and these people are rarely one in the same.
And, just because I'm a geek, and can't help myself, here's what I whipped up in a couple of minutes. I'm sure it could be better, but that's when you start up an interesting conversation about refactoring in the interview, right? ;-)
for i in range(1, 101):
x = ""
if i % 3 == 0:
x = x + "Fizz"
if i % 5 == 0:
x = x + "Buzz"
if x == "":
x = str(i)
print x
I'm very impressed with all of these FizzBuzz developers posting here in the comments!
Has anyone thought of creating a web page where we can see cross-language solutions to the FizzBuzz problem? Once there are enough solutions (and optimizations) posted, perhaps it can be spun off into the Great FizzBuzz Programming Shootout. And don't forget a job board and forums to connect with prospective employers.
This is an exciting time to be in software development.
Brandon Corfman on February 27, 2007 5:54 AMLKM: I think your man was just pointing out that it's a bit dodgy to say "use a stack instead of recursion". Recursion pretty much always uses a stack, you're just talking about using a smaller, faster stack. A stack on the stack, even.
Eam on February 27, 2007 5:55 AMAnyone who expects a VBA programmer to write "swap two variables without using a temp variable" code is going to end up hiring a programmer who gets bored in three months and leaves.
The FizzBuzz problem is a good example of taking a simple set of requirements and translating them into program code.
Unless you're interviewing for an embedded software position, the "swap two variables with no temp" problem is a good example of utterly pointless "Let's see if you know the same nifty trick I know" interviewing. You might as well ask the interviewee where they bury the survivors when a plane crashes on the border of Canada and the U.S.
Kyralessa on February 27, 2007 5:55 AMOkay, so python's required indenting and blogging don't seem to go well together. Ah well, you all know what I meant. ;-)
Edward S. Marshall on February 27, 2007 5:56 AMHere's my simple C program that implements the fuzzbuzz program.
#include <stdio.h>
int main(void)
{
int i,j=0;
for(i=0;i<=100;i++)
{
if((i%3)==0)
{
printf("Fizz");
j=1;
}
if((i%5)==0)
{
printf("Buzz");
j=1;
}
if(!j)
{
printf("%d",i);
}
printf("\n");
j=0;
}
}
well ... someone had to write it in C right?
#include "stdio.h"
int main ()
{
for(int i = 1; i < 101; i++)
{
if (i%3==0) printf("Fizz");
if (i%5==0) printf("Buzz");
if (i%3 && i%5) printf("%d", i);
printf("\n");
}
return (0);
}
I use recursion every day. It makes handling XML simple. I can't imagine not using it. However, if I were hiring someone, I'd not make it a prerequisite. Neither would I fail them if they didn't know what a modulo was. I'd be happy if they could solve FizzBuzz in 30 minutes. I'm more concerned that they understand a little about abstraction. If they don't know what "this" is, then we're screwed.
tutash on February 27, 2007 6:03 AMCF (SCRIPT) version, for your viewing pleasure...
for (i = 1; i LTE 100; i = i + 1) {
if ((j MOD 3) AND (j MOD 5)) {
WriteOutput(i);
} else {
if (NOT j MOD 3) {WriteOutput('FIZZ');}
if (NOT j MOD 5) {WriteOutput('BUZZ');}
}
WriteOutput(chr(13) & chr(10));
}
Opps... I suppose i should have a "return(0);" before that last curly bracket...
I guess that's what I get for compiling without -Wall ...
a_programmer on February 27, 2007 6:05 AM>I think your man was just pointing out
>that it's a bit dodgy to say "use a
>stack instead of recursion".
Well, that's not what I said. I said "Instead of using recursion, it's often faster to use a Stack." Which is true.
>Recursion pretty much always uses a stack,
Yeah, but that does not change what I wrote. Coincidentially, I have written a Java-to-native compiler and happen to know how call stacks are implemented, and the overhead involved in building them up and tearing them down :-)
LKM on February 27, 2007 6:07 AMmost people are in it for the money. most people, like me, actually enjoy coding. What do I do before heading to bed? No, I dont read a book, I code. I get butteryflies in my stomach whenever my professors anounce a new C++ programming project; I start on it that same day and do not stop until complete--and perfect. I added a feature to that fizz-buzz program: it prints out the number which is divisible as well. Took me all of 30 seconds to do.
for(int loop = 1; loop <= 100; loop++)
{
if ((loop % 3 == 0) & (loop % 5 == 0))
{
cout << loop << ":\tFizzBuzz" << endl ;
}else if (loop % 3 == 0)
{
cout << loop << ":\tFizz" << endl ;
}
else if (loop % 5 == 0)
{
cout << loop << ":\tBuzz" << endl ;
}
}
btw, my fiance gets mad when i code early in the morning; i actually had to alt-tab out of the compiler so she wouldnt see it. :P
And the obligatory Haskeller chimes in with:
fizzbuzz n | n `mod` 15 == 0 = "FizzBuzz"
| n `mod` 5 == 0 = "Buzz"
| n `mod` 3 == 0 = "Fizz"
fizzbuzz n = show n
main = mapM_ (putStrLn . fizzbuzz) [1..100]
That probably won't format properly because HTML is disallowed and there's no preview button. What's up with that?
Neil on February 27, 2007 6:10 AM
And now for something completely different. In Lisp. Recursive. And in backwards recursion. For no reason.
(defun fizzbuzz (n)
(when (> n 0)
(fizzbuzz (- n 1))
(format t "~a~%"
(if (= (mod n 3) 0)
(if (= (mod n 5) 0) "FizzBuzz" "Fizz")
(if (= (mod n 5) 0) "Buzz" n)))))
(progn (fizzbuzz 100) (values))
A simpler question, requiring NO answer: If you were writing a disk based index for fast access to usernames from id's, what datastructure would you use?
Blank Stare = Fail.
Eyes light up with passion = Hire on the spot.
Note that the FizzBuzz Test requires at least some simple number theory thinking. Yes, some small children understand it, but most people with standard schooling are not comfortable with the ideas of multiples, common factors, modular arithmetic, etc.
I only point this out because 199 out of 200 should make us question ourselves about the test. I'll accept that 90% of so-called programmers are "low functioning" but not 99.5%.
Is this FizzBuzz-style number theory knowledge required for programming? No. Does it help? Yes, a lot. I find applied mathematical knowledge to be a better indicator of quality, efficient, expandable programming than a checklist of fad languages and environments.
But, still, watch out for hiring *only* super-nerds or your product will be super clever but unusable by "normal" people. A little bit of variety of backgrounds helps.
Dave on February 27, 2007 6:22 AM"Beware of bugs in the above code. I have proven it correct; I have not actually tried it." -Knuth
David H. on February 27, 2007 6:24 AMha ha. Lets see some ASM code. You got 10 seconds. Assuming 8086.
Adrian on February 27, 2007 6:25 AMWhat a whiny post. You complain about the graduates themselves but what about the departments who taught them? If you were really concerned with the situation, rather then obliquely congratulating yourself on being so shit-hot, why not attack the professors?
PhDs do research, not programming and I've know dozens of apparently dim graduates turn into excellent developers.
James on February 27, 2007 6:26 AMpiece of cake. took me about a minute to write it in php
then again, i started my days hacking Z80 assembly on a ZX Spectrum...
maybe this lack of "real programmers" is because of the growth of object oriented languages + visual GUIs - and move away from being at the coalface?
here's "fizzbuzz" in php:
for ($x=1;$x<=100;$x++)
{
if ($x%3==0 and $x%5==0)
{
print "$x\tfizzbuzz\n";
}
elseif ($x%3==0)
{
print "$x\tfizz\n";
}
elseif ($x%5==0)
{
print "$x\tbuzz"."\n";
}
else
{
print "$x\n";
}
}
I once interviewed a guy who TAUGHT programming at a city college and HE couldn't answer very basic questions about the language. My typical C++ interview question is to ask whether they understand what happens when an exception is thrown, stack unwinding, how it can cause memory leaks, and what to do about it. (someone out there is thinking the answer is "program in Java" but they should go die now)
Keith Wright on February 27, 2007 6:28 AMI suspect the original observation can actually be generalized to almost any other profession/job. It seems a common complaint that one has to search hard for even basic skills and then harder for someone who will put the effort into being an employee that can be counted on to even show up regularly and actually work.
One wonders what the future holds when you read the above posts, realize that a fair number of good programmers will be leaving the market over the next decade (boomers), and hear reports of declining enrollments in the field.
I wonder how often this book is read anymore:
http://www.amazon.com/Algorithms-Structures-Prentice-Hall-Automatic-Computation/dp/0130224189
A sad fact is that many of these types of skills often don't apply in business programming, and so you lose touch. Many of the exciting routines we used to learn just don't apply. A little sad.
How about asking people the pros/cons of various types of sorting algorithms?
http://linux.wku.edu/~lamonml/algor/
Steve on February 27, 2007 6:30 AMNot sure what kind of educations you have over there but certainly here in Sweden you write A LOT of code if you study computer science on university or college elevel.
Even in high school programming courses you write code from day one, are you seriously saying this is not the case in the US ??
The whole thing sounds very strange to me.
PL on February 27, 2007 6:30 AMAn APL one-liner where INDEX ORIGIN is 0 :
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W{assign}(100×~0=W)+W{assign}{declose}+/1 2×0=3 5|{enclose}L{assign}1+{index}100]
"{index}100" creates a numeric vector from 0 to 99, "1+" brings it up to 1..100, which we {assign} to L.
"0=3 5|{enclose}L" compute the modulo of 3 and 5 for L. Enclosing vector L makes it a scalar, which can then be taken as argument of a modulo (primitives in APL requires vectors of same length on each side, or a vector and a scalar, the latter being applied to each item of said vector). This gives us a vector of two vectors (one for modulo 3, the other for modulo 5). "0=" gives us two binary vector where 1s point every solution where the number is a multiple of either 3 or 5.
"W{assign}{declose}+/1 2×" multiplies these vectors by 1 and two respectively (now 1s represent modulo 3, and 2s represent modulo 5), and then we sum the two vectors. "/" is an operator which introduce the function between each item of a vector : +/1 2 3 <=> 1 + 2 + 3
In this case : +/(0 0 1 0 0 1 ...)(0 0 0 0 2 0 ...) <=> (0 0 1 0 0 1 ...) + (0 0 0 0 2 0 ...). Since the result is still a vector of vectors (with only one item), we {declose} it, which makes it a simple vector, and {assign} it to W.
"W{assign}(100×~W=0)+" : we then add this vector to another where every number not 0 is replaced by 100. "~W=0" (~ means not) creates a binary vector with 1s everywhere that's not 0, which we multiply by 100. So now we have (0 0 101 0 102 0 ...). We {assign} it to W.
"¯1+(L×W=0)+" : we use the reverse operation "=0" to create a binary vector with 1s everywhere that's not a multiple of 3 or 5 and "L×" to replace every 1 with the original number. We then add this to W, and "voilà !", every number a multiple of 3 or 5 or both is replaced by 101, 102 or 103. Since indexing starts from 0, we substract 1 from the vector "¯1+" (- is reserved for substraction, ¯ indicates negative numbers : 3-¯1 = 4).
"(L,'Fizz' 'Buzz' 'FizzBuzz')[ ...the rest... ]" creates a vector where 'Fizz', 'Buzz' and 'FizzBuzz' are concatenated at the end of L, and [] indicates that we use what's inside the brackets to index the vector to the left : 'abc'[1 0 2] => 'bac'
And there you go : Fizz, Buzz and FizzBuzz replace multiples of 3, 5 or both.
It is possible to create more readable code, but not as fun !
This code, which can be the body of a function, does the same thing in easy to read steps :
List{assign}1+{index}100
Fizz{assign}0=3|List
Buzz{assign}2×0=5|L
W{assign}Fizz+Buzz
W{assign}W+100×~0=W
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(List×W=0)+W]
The original post and the original quoted post do nothing except perpetuate the worst stereotype of what a good coder is. Executive managers prefer to think of their best developers as sweaty grubs who pound the keyboard (rapidly, I'm sure) and who amuse themselves with anal debates. Most of the comments here seem to confirm that stereotype willy-nilly.
"I’ve also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution."
Perhaps they became senior programmers by acquiring the habit of quiet reflection *before* pounding the keyboard (rapidly). Many executives do not understand that the person staring out the window may be getting more done than the busy people at the keyboard.
Job interviews structured to find sweaty grubs will probably find sweaty grubs...
Brett Merkey on February 27, 2007 6:31 AMMy simple C version:
#include <stdio.h>
int
main (void)
{
int i;
for (i=1; i<101; i++) {
if ((i % 3 == 0) && (i % 5 == 0)) {
printf ("FizzBuzz\n");
} else if (i % 3 == 0) {
printf ("Fizz\n");
} else if (i % 5 == 0) {
printf ("Buzz\n");
} else {
printf ("%d\n", i);
}
}
return 0;
}
You all are using the wrong language. Stare in awe at the power of Perl:
use FizzBuzz;
my $fb = new FizzBuzz;
$fb->print;
Isn't this an issue because you can learn to people to master a programming language but not how to solve problems? The people who couldn't solve the fizzbuzz test you describe in your article, might be great at solving well defined problems. I remember Jon Udell wrote an article about the tacit dimension of tech support:
I clearly see "problem solving" as the skill that defines what you expect to be a good programmer.
Casper on February 27, 2007 6:35 AMAs I'm reading this blog topic and all the responses I'm having a hard time breathing for all the smug in the atmosphere (or, rather, blogosphere.)
Oh, I'm such a great programmer that I can't imagince that a professional programmer can't do hexadecimal maths, says the crowd. Look, I'm a relatively new programmer. I do exclusively VB.Net but I work daily in several applications (some in-house, and some production) and I've been programming now for over a year and a half. It was very hard at first, but I'm becoming more proficient every day. One day, I know, I'll be very good but I'm certainly not there yet. You see, I made a career change. Many of you grew up with computers -- tinkering with them, writing programs when you were eight, etc. I don't have that background. After years in the military I got out and decided I wanted to challenge myself and become a computer programmer. So I went to a two-year college, got a degree and got my foot in the door at a small software company.
If you're asking me, I'll say I've done well. I'm also probably being realistic when I say I'll never work as a hotshot programmer for Microsoft. But, you know, there are plenty of programmers out there who aren't superstars. They don't need to be. They are proficient and reliable and they get the job done. Just not superstars that eat, sleep and breathe programming. Does that mean they don't deserve to be programmers?
I understand the point of this blog -- but I just think some of you should step back and take a look at your egos. Because some of you might not have hired me and you'd have lost out on a good programmer. BTW the FizzBuzz thing would have been no problem, but I have no freaking idea what Hexadecimal maths is (it's off to wikipedia!)
Just my two cents. Narf.
Ken on February 27, 2007 6:37 AMI agree it is scary how few people can actually code. That being said, which version is better?
for (x=1;x<101;x++)
{
sprintf(temp,"%s",x%3 ? "":"fizz");
sprintf(tem1,"%s",x%5 ? "":"buzz");
strcat(temp,tem1);
if (!temp[0])
sprintf(temp,"%d",x);
printf("%s\n",temp);
}
for (x=1;x<101;x++)
{
if (!(x%3) && !(x%5))
printf("fizzbuzz\n");
else if (!(x%3))
printf("fizz\n");
else if (!(x%5))
printf("buzz\n");
else
printf("%d\n",x);
}
Jeff, I like your FizzBuzz question, but my use of it in screening would be different, since I see an entirely different problem in hiring a programmer.
I'd try to sit down with the candidate, ask her to do the "FizzBuzz dance" & then wait to see what she does next.
I would be disapointed not to hear some questions, like
"why should she write this code."
"should the code be maintainable, fast, memory economic or is it a show piece?"
"might the requirements change."
before she starts coding ..
After she presents a first solution, I'd change some requirements, crticise some aspect of the code (is a repeated execution of the modulo function needed/efficient, don't you know more about the sequence of numbers your processing ..)... and learn not only "can she code" (in my experience, they usually can..), but can she think, does she stand up for her beliefs, does she spot incomplete requirements, can she point out the faults politely?
Only 10% of the day are taken up by coding .. much of the rest of the time is spent interacting with the designer/architekt/manager/customer.. that's where most programmers I've employed in the past have not failed, but struggled.
When testing for language competence in my graduate class, I have the students write a program at home, but then ask them to modify it in class. While they could cheat and use a "tutor" to write the code at home - if they can't change it and run the resulting program in front of me then there is no way they can code. This eliminates a lot of the test anxiety stress which affects about 1/4 of the students while accomplishing most of its purpose.
Back in the dark ages when I was a contract programmer for about 6 months the contracting company had a neat way to do a similar test. They let you get familiar with the system and environment for about a week and then gave you a realistic problem. If you did it you were still there next week. (I don't know what happens if you didn't).
Robert Harrison on February 27, 2007 6:42 AMHaha, that's why we outsourcers get these jobs instead of some lame US graduates
I think this blog entry would have been better off at thedailywtf.com because it just has to be complete BS, if they have any kind of computer course and the paper isn't falsified of course they know how to solve that, if they don't then you have a serious issue in your education system.
Maybe if you stop wasting so much money bombing people and spend it on education instead ?? Just an idea.
PL on February 27, 2007 6:45 AMI think the point isn't that any one of us (most likely) could spit out a solution to the Fizzbuzz problem in a minute - I had a solution in my head before I'd really tried to think about it. The point is that people go into 'programming' jobs sometimes for the wrong reasons. Maybe because the money is good. I don't know. But these are exactly the kind of folks that need to be encouraged to look elsewhere - and I mean a different career path - for employment. Encouraging folks with no aptitude for problem solving and logical thinking to work in a field where such an aptitude is needed simply drags down the team.
The problem I've seen in the past is that often those doing the interviews aren't qualified to know the difference between a person in a suit with a smile and a good disposition from a person that will actually be a productive member of an organization. This is particularly the case in larger organizations I've worked within.
Any organization that doesn't actively try to find the best people deserves what they get in my opinion.
Matthew Cuba on February 27, 2007 6:46 AMI actually code primarily in python for its cleanliness and maintainability plus convenient methods for handling various data types, but... For the sake of curiosity, I figured I'd go for the executable line noise version (e.g. perl)
perl -e 'for (my $i=1; $i<=100; $i++) {($i%3==0 and $i%5==0)?print "FizzBuzz\n":(($i%3==0) ? print "Fizz\n":(($i%5==0) ? print "Buzz\n" : print "$i\n"))}'
Eric Elinow on February 27, 2007 6:48 AMI can sort of understand this problem, actually (no, not fizzbuzz - that one I get).
I graduated from a major CS school a decade ago - but the school was a Comptuer Science school - heavy on the science - not a computer engineering school. I had classes on Kleene stars and turning machines and all sorts of academic languages that I was unlikely to see again unless I went into computational linguistics. My token database class spent exactly a week on SQL - and, I suppose, with reason...that's "IT", not "CS" in their view. Of course, since I graduated I've written SQL pretty much every day of my career. We spent a lot of time discussing the finer points of various languages, spent a lot of effort writing applications that used these finer points, but didn't bother to spend much time on "what you would actually use these things for in the Real World." That fell outside the realm of "CS" again. I guess the assumption was that this is academia, not a trade school.
Of course, on the flip side, the IT program at the same school required only the most basic programming classes and a lot of business stuff. CS gave you all sorts of cool architectural techniques but few basic skills to use them, and IT gave you all sorts of practical basics but few techniques. There was a huge range in the middle where "actual programming" fell that was never addressed.
I'm not even going to go into some of the small schools with the build-your-own-degree programs.
The only reason I was ever able to hold a job or write some code immediately out of school was because of some hotshot programmer friends who showed me some stuff. Blind luck, basically.
So collegiate education seems to fall short. But that's only really a small part of the problem. From the day I started my post-college career I've been in the minority in every IT department I've ever been in - I'm usually the only person with a formal background in technology. Many people in your standard corporate IT-development department landed there by accident or by lateral move - their training includes "Teach Yoruself VB4 in 21 Days" or maybe a few classes at the local community college. I've worked with plenty of people who consider copy-paste in visual studio "code reuse", and I wouldn't say this any fault of their own - they've just never been shown what OO or even really decent procedural code looks like.
And there's the web...web development allows a lot of sloppy code to slide under the radar, it seems. If a developer has never had to solve a problem because a web browser front end lets them get away with it, they're never going to think about that problem in the first place.
I'm not sure what the solution really is - it'd be nice to have the education broaden a bit from both directions, but that will only help people who are exposed to it in the first place, which isn't often the case. Working with a good programmer helps immensely - it's what kept me from being useless for years, and I've seen one guy's good code transform the coding styles of entire companies in a matter of weeks - but how to do you guarantee a good coder in your environment?
Something to ponder, I guess.
Eric on February 27, 2007 6:48 AMTo answer your original question: I've worked on big projects where the low-level programmers (and me, the contractor,) spent weeks or months doing cut, paste, change-the-variable-and-function-names kind of work. A person can sit in front of a computer and "program" for a long time without ever having to actually write even simple logic from scratch.
Maybe this is the "experience" your seeing on people's resumes.
It is interesting that at least two solutions given in the comments are wrong. People don't even know that they can't program.
lall on February 27, 2007 6:54 AMwow.. pretty scary thought.
Interestingly, in the USA (at least in massachusetts where i am from), we used to play the same game but it was called "BizzBuzz", not "FizzFuzz".
So here is an American BizzBuzz version in Python:
-------------------------
#!/usr/bin/env python
for num in range(1, 101):
if not num % 3:
print "bizz"
elif not num % 5:
print "buzz"
else:
print num
-------------------------
lua is nice!
for i=1,100 do
fizz= (i%3==0) and "Fizz" or ""
buzz= (i%5==0) and "Buzz" or ""
print(i,fizz..buzz)
end
I've become infected with the FizzBuzz fever, too.
main = putStr . unlines .
foldr (zipWith ($)) (map show [1..100]) $
[replace "FizzBuzz" 15, replace "Buzz" 5, replace "Fizz" 3]
replace s n = fix ((replicate (n-1) id ++ [const s]) ++)
Console.Writeline("1");
Console.Writeline("2");
Console.Writeline("Fizz");
Console.Writeline("4");
Console.Writeline("Buzz");
Console.Writeline("Fizz");
Console.Writeline("7");
Console.Writeline("8");
.
.
.
Yeah it's not elegant (on purpose). But it shows that I can follow the directions and produce code that works. If the interviewer wants to do a code review and ask me to defend my methodology, I'm happy to do so.
Can anyone post the answer to the vowel/even number logic puzzle. I hate logic puzzles, but the programmer/pessimist in me says all 4 because you never know what the next input would be. However, I'm guessing the answer he wants is "A" and "2"?
Mike H on February 27, 2007 7:00 AMto LKM:
i am sorry if you felt my message as hostile. english is not my native language and i may sometimes seem a bit rude (i do seem rude anyway on my daily life). it was not meant to be offensive at all, and i deeply apologize if you took it that way.
anyway:
"Do you understand that by using a local stack instead of the call stack, the computer needs to keep track of much less information and needs to do much less work building and tearing down the call stack? In most languages, using a stack instead of recursion speeds up your app tremendously."
yes i do understand. it is just less error prone to let the computer do the stack keeping for you. also, a good compiler will have a good optimizer which will make handcrafted optimization look slow (unfortunately, apart from tail recursion, recursion is not the favorite playground of optimizers).
but, as always, the solution used to solve the problem will depend greatly on the domain you are coding for. you will not code the same algorithm for an embedded system, a large-scale data-center or a desktop application. you will definitely have to make tradeoffs between resource usage, reliability, and ease of programming.
rien on February 27, 2007 7:01 AMPerhaps I'm failing my Sense Motive roll, but I'm truly saddened by the number of people who not only posted the solution, but posted the *wrong* solution.
Go back and count the "solutions" that failed to print the values from 1 to 100. Go back and count the solutions that started a loop at zero instead of one.
So sad. I really hope that they were deliberately wrong to keep the script kiddies from getting a job. In fact, my sanity requires that I chose to believe that.
Randolpho on February 27, 2007 7:04 AMint main() {
printf("Get back to work!\n");
return 0;
}
rien: I guess something was lost in translation then :-)
Sure, creating your own stack has its own sets of problems, and it's not suitable to replace all usages of recursion. It's often a good idea, though. I'd say that using a stack instead of recursion is not so much "handcrafted optimization" as it is "avoiding expensive patterns where they are not needed" :-)
LKM on February 27, 2007 7:09 AMFortunately, coding is merely my hobby. The one time I applied for a job, I did have to do some basic code in front of the owner of the company. He asked me to do something basic that I hadn't done in C in many years, so I couldn't remember the commands, so I had to resort to the last language in which I had actually done it: REALbasic. That was a bit embarrassing, to say the least. I also had to recode the script in front of him, because I wrote it under a minute and had a few logical errors in it, which I corrected. Then I optimized it in front of him, which I couldn't walk away without doing. I didn't get the job (thankfully), but I was one of the top two candidates. The only thing that won out the other guy in the end was that he had more experience with .NET than I did. Or so they told me. Could very well have been that I was a colossal embarrassment, but they were too kind to tell me. Who knows? But I do know that I'm glad I didn't get the job. I just haven't got the chops to sit in a room and code all day, not even for pay.
Jae on February 27, 2007 7:09 AMSo, exactly where are you FINDING these job candidates? sounds like a piss poor advertising and recruiting practice if 99.5% are not valid candidates.
Geesh, I advertise on Craigslist in Austin or Phoenix and over 1/2 of the people who apply are able to pass a test like this. And this is with modest pay for an easy and flexible work at home job (ssh, svn, etc). Plus I get maybe 10 to 15 replies running the advertising 1 time, and those replies come in within the first 5 days. So I get 5 to 8 real job candidates and I can focus on long-term aspects of which person is best.
In other words, just like writing a good resume is important, writing a good job description and knowing where to find people is just as important.
Stephen Gutknecht on February 27, 2007 7:10 AMFor some reason,(maybe because I am now only a hobbiest) I still use qbasic for brainstorming and pseudo-code)
X=0
Do
X = X + 1
outstring$ = ""
If x mod 3 = 0 then outstring$ = "Fizz"
if x mod 5 = 0 then outstring$ = outstring$ + "Bizz"
if len(outstring$) = 0 then outstring$ = str$(x(
print outstring$
Loop Until X = 100
Here's a "clear" Lisp version:
(defun fizz-buzz ()
(loop for i from 1 to 100
do (cond
((= 0 (mod i 3) (mod i 5)) (format t "FizzBuzz~%"))
((= 0 (mod i 5)) (format t "Buzz~%"))
((= 0 (mod i 3)) (format t "Fizz~%"))
(t (format t "~a~%" i)))))
lua still nice even doing what the problem states!
for i=1,100 do
fizz= (i%3==0) and "Fizz" or ""
buzz= (i%5==0) and "Buzz" or ""
number= not ((fizz=="") and (buzz=="")) and "" or i
print(number..fizz..buzz)
end
"It is interesting that at least two solutions given in the comments are wrong. People don't even know that they can't program."
People might know how to program, they just don't test what they program!
José Rui Abreu Mira on February 27, 2007 7:13 AMIf I'd been given the "swap 2 values with no temp variable" problem before yesterday, I probably would have said "you can't do it".
Now that I've seen the trick (which isn't a general solution. It only works for integers, and only those containing values that won't overflow when added), I probably would have said "you shouldn't".
I've been developing software professionally for 18 years now, for fun about 9 years before that, and have at least 6 assorted Free or Public Domain projects under my belt. Does my "incorrect" answer to that question make me a bad programmer in your eyes? Given that your "correct" answer is something I'd slap someone for trying in any code I have to maintain, I think I'd prefer to not get that job anyway.
As for the issue about recursion, in my experience most software developers (even fairly good ones) are scared of it. I wouldn't consider that a deal-killer for hiring. I was scared of it too, until I took a Lisp course in college. Its probably a better test of Lisp exposure than anything else.
On the other hand, if you are scared of it, be honest enough to admit it. Don't throw me some (possibly true) pablum about explicitly using a stack being just as good, and faster in some cases.
If an algorithm is naturally recursive, recursion is probably the best expression of that. As for the speed issue, I agree that a good programmer doesn't do things that are going to be massively slow. However, they also don't pervert their source code for optimization purposes. That's the compiler's job. If the compiler fails, *and* you have a known speed problem, *and* you have tracked a big bottleneck down to that chunk of code, then you may source-level optimize. Otherwise, just make it as understandable as you can, please.
However, I would consider "I have trouble with recursion, and so does nearly every other developer who will have to maintain this code", a compelling argument.
T.E.D. on February 27, 2007 7:15 AMI interviewed at a place with a fairly stringent testing regime last year. There were many "write on the board" SQL questions and some Java pair programming with one of the team leaders.
Unfortunately, although I nailed the whiteboard part, I did poorly on the pair programming portion. I didn't handle the context shift between VB (which I was using on the current gig) and Java well enough, and kept foolishly expecting Eclipse to get the case on my variables correct for me, leaving off semicolons, stuff like that. It was embarrassing, considering that six to eight months previously I had been doing a lot of Java.
I suppose I would have done better had I freshened my Java knowledge a little before the interview, but I had an informal offer on the table for a lot more money and was going through with this interview for, shall we say, domestic political reasons (i.e. my wife didn't think the existing offer was official enough and would have killed me if I'd cancelled this interview. Because of the pay discrepancy and the awkwardness that would have ensued in trying to negotiate an informal offer against an inferior, but formal one, I actually dreaded the prospect of an offer.)
Highly Paid Consultant on February 27, 2007 7:15 AMSome of these tests are fine, but I'm sorry... OCTAL? Almost -nobody- uses octal anymore. You're rewarding programmers for learning stuff they'll never have to use. If they ever need it for some crazy reason, they can always use google and spend two minutes learning how to interpret it.
These tests can't determine whether a programmer is economical, which is the secret to what actually makes programmers good. I've seen many programmers who are much smarter than I am destroy projects, because they spent too much time hacking on the 20/80 stuff instead of picking their programming battles wisely. Good programmers get the job done, which is why the best test for programmers should be their ability to create stuff (like projects, OSS and whatnot).
(python)
for i in range(1,100):
if i % 15 == 0: print(str(i) + ' fizzbuzz')
elif i % 5 == 0: print(str(i) + ' buzz')
elif i % 3 == 0: print(str(i) + ' fizz')
(c#)
for (int i=1; i<=100; i++)
{
if(i % 15==0) Console.WriteLine(string.Concat(i, " FizzBuzz"));
else if(i % 5 == 0) Console.WriteLine(string.Concat(i, " Buzz"));
else if(i %3 == 0) Console.WriteLine(string.Concat(i, " Fizz"));
}
I had recently gone through a few interviews - some good and some bad.
I thoroughly enjoyed one in particular for Blackbaud (Charleston, SC) where the team lead asked me through some real basic questions (something like storing people's favorite activities) that covered relational database, OO, and web-based design concepts. Nothing particular hard - but worthy of actual thinking. Then she went and expanded the basics a few times and had me explain what I would do - which covered nicely aspects of software maintenance that I reasonably expect most get to deal with. I did get the offer, but couldn't take it (in the end) because I had hoped I would sell a house in another state ... it was very complicated :)
Then I think back to another interview where there was a programming test. And I just completely bombed it ... I mean TOTAL brain fart. How embarrassing! I've gone through others and did completely well, but like how some interviews go (or at least for me), some go really well, and some just don't. Including programming tests. Well, the job was probably too far west (San Francisco) for my family anyway...
Chris Harmon on February 27, 2007 7:20 AMWe've had a fair number of interviewees who couldn't write a very simple program. But I bet a fair number got home and realized that they could do the task easily under normal conditions, but had freaked out with interview anxiety.
Andrew Webb on February 27, 2007 7:21 AMseq 1 100 | sed '0~3 s/[[:digit:]]*$/Fizz/
0~5 s/[[:digit:]]*$/Buzz/'
While I understand the problem of programmers who can not program I really have no empathy for those of you doing the hiring.
I went to a little community college and got an A.A. while there I learned to program in C/C++, pascal, cobol, QB, and AS400. Since college I have taught myself 3 new languages and if I were to interview for a programming job would have brushed up on the syntax enough to have easily passed any of the "tests" listed on this page, yet none of you would have let me get that far.
Since I have only an A.A. no one seems to want to even bother interviewing me much less test me to see if I "have the skills". Yet they fall all over each other trying to "catch" one of the kids that used to come to me for help on their assignments week after week. Because those same kids went on to get a B.A. or a B.S. while I decided I was deep enough in debt and went out into the world to do basic comp. repairs.
It has been my experience that those who programmers who fail your little tests are most likely failing not because they can't program but because they have a problem applying their knowledge (it is a fine line but a valid one). Much like most high school grads these days seem to know the basics of proper grammar but could not compose a decent letter to save their lives.
That's my opinion anyway, take it for what it is worth.
quote: it's the standard a=a+b, b=a-b, a=a-b problem
Hopefully a and b aren't near MAX_INTEGER. In fact this is a worse solution than doing something obviously wrong as it will only come up in the weird cases making it even harder to debug. This is a terrible way of doing it, you fail!
BlogReader on February 27, 2007 7:27 AMToepopper wrote
Very very common, alas. I once interviewed a candidate for a VBA job (yes, you can stop booing for the peanut gallery) whom I asked to swap two variable contents without using a temp variable. It's the standard a=a+b, b=a-b, a=a-b problem. His answer? Well, I can't do it in VBA, but if you let me use Excel I can put the values in two cells and swap the cells' contents using a third cell.
We hired the guy who said, well, "if they're integers, then I'd do it by a=a|b, b=a^b, a=a^b. But I don't know how to do it if they're strings."
Toepopper on February 27, 2007 01:49 AM
I think Toepopper hired the wrong fellow, because his "swap program"
is logically flawed. After looking up the meaning of the | ^ operators (i.e. | = bitwise OR and ^ = bitwise XOR), I attempted a formal proof. I could not get it to work out. So I tried a simple case. Suppose we have 1-bit words and
a = 1
b = 1
After a = a|b:
a = 1
After b = a^b
b = 0
After a = a^b
a = 1
And you can see, a swap has not occurred.
R. Butler on February 27, 2007 7:29 AMECMAScript Solution:
function fizzBuzz(lim) { var msg=''; for (var i=1; i<lim+1; i++) msg += (i%3==0 && i%7==0?'FizzBuzz':(i%3==0?'Fizz':(i%7==0?'Buzz':i)))+' '; return msg; }
Jim R. Wilson (jimbojw) on February 27, 2007 7:34 AMHi!
I am writing from India.India is becoming famous with IT and lot of software development stuff happening here.
But,to my surprise,people in large organizations hires the candidates from the campuses with bulk entity and not even asking any fizz buzz questions.
I have given number of test with smaller organizations which requires to pass technical test or code right away at the time of test.
and I opted for such a company.Now,reading this article I think my decision is *really* good.
Another point to be made is should *years of experience* really teaches us these things in programming???
and if no then why do all software companies ad mentions the years of experience instead of asking for some other point...
please comment..
Lalit on February 27, 2007 7:34 AMIt seems to me that most of the comments here are focused on the actual code solution for the FizzBuzz question. I would like to step back and talk about the actual lack of programming knowledge possessed by those that apply for these programming jobs. I would say that the reason that so many numbskulls apply for these jobs is because somewhere in the job requirements it says that applicants must have at least a Bachelors in computer science. Most of the best programmers I have ever known, including myself, do not have a degree of any kind, and in my case, never went to college. Yet, many companies will simply push your resume aside if they see that you do not have the required degree, no matter what you skill level may be. A degree is just a piece of paper that says that you have sat in a class for x number of hours learning about something that you may or may not remember when you leave. If companies want to find real programmers with real programming experience they need to broaden their search or have a little slack when it comes to their job requirements. I guarantee that they will interview many more applicants with a deeper knowledge of the force.
Anthony Decena on February 27, 2007 7:35 AMDave: "Note that the FizzBuzz Test requires at least some simple number theory thinking."
It's extremely simple number theory thinking, that people in all fields should know. The word "multiple" is basic vocabulary, and any grown-up with an IQ over 80 ought to be able to understand what it means.
Ben Atkin on February 27, 2007 7:38 AMThat's a relief. I'm like "Dang! What if I'm one of the ones who can't do that?!" The script below is probably a little inelegant, but it works. Took about 5 minutes, but part of that was talking to a co-worker about nasal irrigation.
<?php
for($i=1; $i<=100; $i++) {
if ($i%3 == 0) echo "Fizz";
if ($i%5 == 0) echo "Buzz";
if ($i%3!=0 && $i%5!=0)
echo $i;
echo "<br>\n";
}
?>
Or how about,
$s = '';
for($i=1; $i<=100; $i++) {
$s .= ($i%3==0)?"Fizz":"";
$s .= ($i%5==0)?"Buzz":"";
$s .= ($i%3!=0 && $i%5!=0)?"$i":"";
$s .= "<br>\n";
}
echo $s;
?>
I prefer readability to compactness.
Mike H, the answer to the vowel/even problem is "A" and "3". It would be all four only if my theory were if-and-only-if, but that's not what I specified.
Jeff, thanks for posting this one, I've found replies really engrossing. Readers identified three problems worth solving:
1. Write FizzBuzz code
2. Distinguish good programmers from lousy ones in an interview
3. Fix the educational system that produces these morans
It's been a pleasure to read proposed answers for all.
John Pirie on February 27, 2007 7:42 AMBig Playa - re-read the requirements... you failed.
I ask the candidate to write a simple but full-fledge class from scratch. (Many can't)
I also provide a series of assertions and ask the candidate to write code that passes those tests.
However, writing code on a whiteboard is hard even for me, and I've written a lot of code in the last 20 years. These days I'd provide the candidate with a laptop (if they don't have one with them) and watch them code and test their code.
Charles Kens on February 27, 2007 7:45 AMAnthony -> thats what i look for when hiring - experience and aptitude over qualifications. and i really dont care how many "certified whatever" post-college qualifications you have either.
a portfolio is essential. past experience too and a willingness to learn. some of the best coders i've met have never gone to college either. the ones that did go to college and were good coders after , were coders in their teens pre-college.
i think the problem lies with folks that never programmed before college and just did the course to get this mythical enormous "I.T. salary", without necessarily having any aptitude or love for the subject.
I dont know a lot of the languages used in here, but im guessin about one fourth of the answers to FizzBuzz are wrong.. I mean:
for num in range(1, 101):
if not num % 3:
print "bizz"
elif not num % 5:
print "buzz"
else:
print num
I dont know Python but that code looks like it doesnt print the bizzbuzz, am I rigth or is Python just weird?
i hope Im wrong cause this is sad..
I can't believe no one has put up the Perl Obfuscated version of the FizzBuzz:
map{$_=(!($_%3)&&!($_%5)?"caddeidd":(!($_%3)?"cadd":(!($_%5)?"eidd":$_)));y/cadei/fizbu/;print"$_\n"}(1..100)
My obfuscation powers are weak this morning, I'm sure it could have been done much better.
Incidentally, if this were the interviewee's answer, I would probably not hire him. I might invite him to become a member of Perl Mongers, though (http://www.pm.org)
TimothyChenAllen on February 27, 2007 7:51 AMAbout 8 years ago, after a UK conference on teaching the new language of Java, one of the attendees said that we certainly needed to change something -- the final year students on the Comp Sci course at his prestigious university were not confident in writing any program, even one just 10 lines long. Other people there agreed that it was not much better, if any, where they worked. Surprised, I went back to my much less prestigious place where all our students took joint degrees, Computing and Maths, Computing and History etc and and checked with my final year OO class. I had real difficulty explaining the question, even though I upped the size to 20 lines -- they just could not imagine anyone on our (half a) degree course, even those who had dropped programming at the earliest opportunity, being unable to write proper programs. What was the difference? Maybe a culture of 100% attendance, and the fact that, not being much of a research establishment, we did not farm out the practical labs to uninterested grad students.
On recursion, I stand by my advice to students. You should know what it is, how it works, and how to program it. But you should _never_ use it in production code, because whoever maintains it may not grasp what is going on.
On swapping the values of two variable without involving a third, I am torn. I agree it is irrelevant to much of modern programming, and is probably not taught in most places. But it does provide a good test to see if someone has read around the subject a bit -- and if they haven't heard of it you could use it like Ben's test to see if their eyes light up when you say it is possible.
Mike Woodhouse - "As I'm about to start looking for a programmer I shall be able to implement my long-cherished plan of asking candidates to submit a page or so of what they consider to be "good code"."
So where can we send our resumes/good code?
And yes, I can write the fizzbuzz thing. :P
Telos on February 27, 2007 7:54 AMI must say, that things like this are necessary. I hired developers for a small low budget startup before and you get any hack who has written HTML applying as a "programmer".
Also, knowledge of the framework is beneficial but does not mean you can write a line of useful code. It means you know how the framework works, and frankly that's what docs are for.
A true "programmer" can write code without knowing the framework and generally the code will run efficiently and well with only minimal need for tweaking to optimize it for the framework it's on.
What is recursion and hexydecimal?
.
.
.
.
.
Sorry, couldn't resist.
It is sort of funny that a lot of people who posted solutions here did not print the actual number on the condition of (i % 3) == (i % 5) == 0. Just goes to show you, being a good developer isn't just about writing code, it's also about reading comprehension! READ THE SPECS!
I also wasn't familiar with the "xor trick" of swapping variables that Toepopper mentioned in his first post and that others have mentioned here. However, I'd like to think it's an indication that I'm a good programmer that I immediately noticed it was suspicious, and a quick google search confirmed that it was in fact wrong (all three operations are xor, whereas the one posted used an "or" on the first one). If that is actually what the interview candidate stated, it would have been a bad sign to me, a sign that either they'd seen the trick before but didn't understand it, or understood the form but not the function (cargo cult).
As others have said, though, the only time I could ever see this being used is in an embedded system. Outside that domain, it's essentially just another brain teaser, one of those things that when you know the answer you go "oh, that's so easy!" but could spend days thinking about if you haven't seen it before. Those of you who keep saying that every competent programmer should know this, please ask yourselves what it says about _you_ that you can't tell the difference between a simple problem with a mundane solution and a "gotcha" question.
A little bit more searching indicates that the xor swap may perform worse than a temporary variable anyway, due to processor pipelining. I'm not sure whether or not that's true, but even if it isn't, compiler optimization would make the two methods at least equal in performance. I also found a post (http://blogs.msdn.com/rick_schaut/archive/2004/03/06/85357.aspx) which asserts that an optimizing compiler might just change all subsequent variable references after a temp-variable swap, which would make the xor swap slower. Stupid code trick indeed.
Bottom line - if I ever saw this "clever" trick used in modern non-embedded code, I would consider it and everything else around it to be suspect. I can't imagine anything worse than a developer using one of these lame tricks and making a typo or getting it wrong, then having to spend days or weeks searching for the source of the problem. That trick is an antique, completely irrelevant to today's programming problems (except maybe if you're writing an optimizing compiler).
Aaron G on February 27, 2007 7:59 AM
all right. At least let's make it interesting.
Post the *tests* for FizzBuzz that you'd write *before* writing code !
Heck, I'll take unit and/or acceptance tests.
What's pretty dang funny is how many of the code examples above are wrong. That shows either one of two things, you misunderstood the requirements, or the even more fatal, YOU DIDN'T TEST YOUR CODE. Also the amount of of bombs we drop on suicidal muslim extremists has no bearing on this topic. As for outsourcing my old boss, when told we needed two more guys for a certain project, would say "OK get me 10 indians".
zetaprime on February 27, 2007 8:02 AMuglydawg: I don't even think a BS is enough these days. Completely unable to find a good programming job with mine. I was lucky enough to get a clerical position at my current company, and then the main programmer for my department left so I stepped in.
The problem is I'm still technically in the clerical position because they won't promote me. :(
Telos on February 27, 2007 8:05 AMThe point of the interview should not be just to find a question that will trip people up. I'd get the swapping variables question wrong (well not any more) but I've generally do better the more technical the interview. It would seem silly to give the FizzBuz test and say "HA! You got the syntax of the modulo operator wrong (while writing the program out longhand under the pressure of an interview and not having tools to unit test it)! You are NOT a programmer!" It's the people like that the database analyst I interviewed who couldn't write a SELECT statement that deserve that ridicule. (Then again you might be looking for an embedded systems engineer who can do the variable swapping thing and not care if they know SQL. It's not one-size-fits-all.)
Marc on February 27, 2007 8:09 AM> Can anyone post the answer to the vowel/even number logic puzzle
I hate these puzzles as well, but because they often hinge on some pedantic phrasing. In "the real world", there is usually some system against when you can test your understanding normally, some shared organizational expectation of the meaning, or some person involved in writing the spec/question you can go to for clarification. (that is, unless you're trying to maliciously follow the spec =-) )
Now I'm not actually familiar with this puzzle, but the phrasing makes the answer pretty clear in my head.
"I have a theory that if there is a vowel on one side of a card, then there will be an even number on the other side"
That is, he says "vowel on one side => even number on other". He's not saying that whenever there's an even number there will be a vowel. He's also not saying that a consonant implies odd number (similar to previous sentence).
You only need to check one card: "B"
Chris on February 27, 2007 8:10 AMI read statements like "demand for programmers is outweighing supply" and "99% of comp sci grads cant write fizzbuzz" and its very encouraging. I didn't go to school for comp sci, but I could write the fizzbuzz in under ten minutes, including the time it took me to figure out how to use g++ from the command line. I'm by no means an excellent programmer, but if most applicants are really that bad, then I think I could be quite competitive. Is that a bad attitude? I'd like to think not, because unlike many people who would apply for these jobs, I have a desire to learn more than what's required to stay employed.
What do you think? Should I not even bother if I'm not already an incredible programmer? Would I just muck up a solid team, or is common practice to "level up" on the job?
Unlike most comp sci grads, I'd be in it for the fun of problem solving, with salary in second place.
blkmage on February 27, 2007 8:15 AMI have to agree with the premise of the article. Most programmers really can't program.
We give a very simple programming test that basically asks applicants to sort a list of names by first and last name. It is pretty trivial. Most applicants either totally botch it or end up giving up after four hours or so. Seriously, it has been the best litmus test we could possibly have hoped for.
Matt on February 27, 2007 8:18 AM
I saw some comments criticizing the poster for providing the answer to the question.
The difference between skills assessment and sadism is that when you are assessing skills you tell the applicant the answer you were looking for. It's supposed to be a learning process for both sides.
Not sharing the answer is intellectual bullying and having been on both sides of the interview table it would make me very leery about a firm that won't answer its own questions.
calenti on February 27, 2007 8:19 AMAt my company we use a considerably more complex programming test, but we only hire "senior" level type programmers, and our job postings specifically state we are looking for senior programmers.
For the java programmers, for example, we require them to write a webpage that will get data from a database, display it, let the user edit it, and save it.
For C programmers it's an exercise in reading and parsing a data file and generating a report of its contents.
These tests also require knowledge a few non-programming things that are pretty basic to the unix programmer (and we include unix in the job postings, so we expect them to know the basics), like telnet and ftp.
Almost all the candidates who take the test literally don't know how to begin. We've had computer science graduates who don't know unix (when I was in college we ONLY used unix, and I'm not *that* old - I never had to do punch cards), who don't understand what IP address is, don't know how to ftp. We rarely get anybody who even makes it so far as to be able to begin writing code. Of the few who make it that far, very few of those manage to write anything worthy of consideration. It takes a looooong time to find acceptable candidates. I suppose senior programmers are less likely to be looking, and when they do they probably use their network more than job boards, but even so, it's pretty depressing. Or entertaining, depending on your outlook...
It's one thing for a person with limited experience, but who has written functioning code, to apply for a senior programmer position, but to not have one single skill requested in the job posting? For a SENIOR position?! I'd like to know what the hell these people are thinking! And we tell them before they come in that there's going to be a technical test, so it's not like it's a surprise when they show up. And even though they know they don't have any of the technical skills being sought, they still show up and waste everybody's time.
Almost all of you fail. The requirements clearly say that for multiples of 3 you are suppose to replace the number and since it is part of the same sentence you can suppose they mean the same for multiples of five. However multiples of both three and five are a totally different requirement and should be printed in addition to the times the multiples of 3 or 5 are printed.
You you could just chalk it up to bad requirements from the user ;)
will dieterich on February 27, 2007 8:26 AM /**
* Faster for a small amount of recursions, breaks without error for larger recursions (in php4)
*/
function fizzBuzzCounter($i=1)
{
if($i>100)return false;else $s='';
if($i%3===0)$s = 'Fizz';
if($i%5===0)$s .= 'Buzz';
echo ($s===''?$i:$s)."<br/>";
return fizzBuzzCounter(++$i);
}
fizzBuzzCounter();
/**
* The obvious solution, alot faster in php5, can handle larger numbers
*/
for($i=1;$i<=100;$i++)
{
if($i%3===0 || $i%5===0)
{
if($i%3===0) echo 'Fizz';
if($i%5===0) echo 'Buzz';
}
else
{
echo $i;
}
echo "<br/>";
}
Wow, double error... I meant to type "A" instead of "B".
And I got lost in my pedantics. You do need to check all 4 cards.
Since, if a vowel is on either side you have to have even on the other... if you have even on one side, the other must therefore be a vowel. And since anything not a vowel is a consonant, and anything not even is odd (ignoring weird cases like "Y" being sometimes one or another), you end up with all 4 cases covered in your theory.
For exampe: If you have the following set A/2, B/2, 2/D, 3/D.
You only check the "A" and "3" card, and your theory looks good.
Except there's an even number on the 3rd card ("2/D"), but there's not a vowel on the back, and you didn't check it, so you missed it.
You missed it -> Theory wasn't adequately tested.
@zetaprime, sure it does, the whole point is that something is wrong in your education system, it seem to concentrate on graduating people with no skills.
The US doesn't even have a decent public school system, or a decent public healthcare system, of course these things have a direct impact on the quality of graduates.
Do you even know how much you spend on the military ? It's completely insane amounts. You alone stand for 1/3 of worlds total military spendings, and thats with less than 10% of the worlds population.
The US is not what I would call a modern country, you may have the gadgets and a great corporate climate but you fail to realize that it's the people that is the country, I can give you a million examples of this but that's a completely different discussion.
The military spendings have a LOT to do with the state of your schools today.
> asking candidates to submit a page or so of what they consider to be
> "good code". I don't mind if they wrote it or not,
All the better if they didn't, since it would indicate that they actually read other peoples' code.
chuck on February 27, 2007 8:36 AM"the count on February 27, 2007 08:20 AM"
are you using employment agencies or are you advertising directly?
if you are using agencies, it could simply be a case of the agencies not giving the candidate the full picture, in the hope that they'll slip under the radar, and Mr Agent will get his/her 10% commission.
that does happen a lot , and its not the candidates fault sometimes.
I certainly agree with the fizzbuzz test in terms of knowing basic things.
However, on the other hand, there's a difference between not knowing specific code/syntax, and not being able to learn it quickly if the need arises.
If you just don't have the mind for the programming, then it doesn't matter what language you use: your code is going to be confusing, messy, and very difficult for anyone else to maintain or build upon.
Mal on February 27, 2007 8:39 AMI've written one student compiler, a Prolog to C translator, numerous small interpreters, major C++ and ksh programs and subsystems, many of which are probably still running in systems around the world. By most standards (faults, easy to maintain, reusable parts), my code has been excellent. Although I would not have trouble with the FizzBuzz program, I do have trouble producing even some simple programs in 10 minutes while someone waits across the table. I suspect that many who can do this produce crap software, because they are willing to start coding before doing any analysis or design.
Jack on February 27, 2007 8:41 AMDifferent perl version. Won't guarantee it's correct, not having a perl runtime on this machine. It's more correct than other solutions I've seen though
for($i = 1; $i <= 100; $i++)
{
$out = "";
$out .= (($i % 3) == 0) ? "fizz" : "";
$out .= (($i % 5) == 0) ? "buzz" : "";
$out .= ($out == "") ? $i : "";
print $out;
}
select case when mod(rownum,5) = 0 and mod(rownum,3) = 0 THEN 'FIZZBUZZ'
When mod(rownum,3) = 0 then 'FIZZ'
when mod(rownum,5) = 0 then 'BUZZ'
else to_char(rownum)
end num_fizz_buzz
from all_objects
where rownum <= 100
I give coding tests to every developer I interview, along the lines of implementing a single method. The method is passed a string of characters, e.g. AABBBBBCCCCDDDEEEEEEEE and it has to return a string holding the longest reocurring character sequence (i.e. "EEEEEEEE" in this case). This is a 10 min exercise, which at the time I started it I tested on colleagues to make sure it was reasonable. You have to allow a lot of leeway for nerves in interviews, and some for unfamiliarity with tools, but it has been absolutely astonishing how few candidates have been able to complete it in 45 minutes. I have even had one guy who seemed absolutely job worthy until this test - and after an hour had only produced an (incorrect) flow diagram on a white board, not even touching the computer.
Jon Vaughan on February 27, 2007 8:43 AMI had a programming interview recently...I really wish they had asked me the FizzBuzz question. Horrible round table generic questions that don't prove, to any measurable degree, my capabilities as a programmer.
Chris on February 27, 2007 8:44 AM"Do you even know how much you spend on the military ?"
thats because the EU doesnt spend its fair share on defence, and thus uses the U.S. military umbrella. therefore, the EU can spend money on welfare, socialised health and very little on defence. so , the argument is somewhat unfair when you stand back and look at the bigger picture.
So, you want a real Professional Association for Software Engineers, eh?
Some places are starting this. For example, the Canadian Council of Professional Engineers has started to certify Software Engineering as an actual Engineering discipline. (Like Civil, Mechanical, Electrical, etc.) That means that you will have to do the following to call yourself a Software Engineer in Canada:
1. Get a 4-year degree, or 5 with co-op.
2. Spend 4 years under the guidance of other Professional Engineers.
3. Advance your skills over those four years.
4. Take a Professional Practice exam.
5. Have your character vouched for by four existing P.Engs.
By the way, there's no damned way you'd use that swapping trick on an embedded system. You're just asking for a world of pain.
First, there's the obvious problem with overflow. Let's say you want to swap 212 and 75 on an 8-bit system. Oops, you've just over-written your program somewhere.
Second, if you try to use cute tricks like that, there's a chance that you'll get interrupted in the middle and end up with the wrong values in your two variables. You can end up writing garbage - sometimes to ports. The correct answer is "You wouldn't do that. It's irresponsible."
It's like the
while( *p++ = *s++ );
strcpy code. Yeah, it works, but it's the worst code in the world.
themagni on February 27, 2007 8:47 AMSimple C answer:
for(i=1 ; i < 101 ; i++){
printf("%d%s%s\n", i, i%3 ? "" : "fizz", i%5 ? "" : "buzz");
}
It's disgusting how many wrong solutions there are to FizzBuzz on this page..
for(int i = 0; i < 100; i++){
if(i % 3 == 0)
printf("Fizz");
if(i % 5 == 0)
printf("Buzz");
else
printf("%d", i);
printf("\n");
}
Chris I haven't seen the card one either, but I don't think you have to flip more than A and 3.
You're testing "if there is a vowel, the number must be even" which doesn't care what number pairs w/ consonants.
So A must be flipped to verify that the other side is even. 3 must be flipped to verify that the other side is NOT a vowel.
But there's no need to check B - it has no vowel.
I assume the "trick" to the problem is the 2 card. You first think "Oh it's even so I have to flip it." But you don't.
If you flip it, what do you get? If it's a consonant, you haven't disproved the theory, because it's okay for a consonant to pair with an even number. If you see a vowel, you have some additional annecdotal evidence to support your theory, but nothing that really means anything.
I must not be in the top 0.5% of programmers, because I've been on more than one or two job inteviews... and I tell you, most of them were terrible at assessing my abilities to think and to code.
After walking out of several interviews convinced the company had done nothing to distinguish me from a tree stump, I got to the point where I almost wanted to shake the worst interviewers and shout "ASK ME SOMETHING HARD!"
I think the only real solution is to make programmers be licensed professionals that need to periodically prove that they have the skills their resume says they do.
I envision something like the Blacksmith Guilds of old ;)
Karthik on February 27, 2007 8:52 AMswapping without using a temporary generates more code than using a temporary.
http://www.codingaway.com/2007/01/31/is-swap-without-temporary-a-good-idea/
Its wrong to think of solutions from programming perspective. I mean why should I know how to use recursion to solve a "real" problem?
First we should be able to define the problem & then find the best possible solution..recursion or no recursion.
"Jon Vaughan on February 27, 2007 08:43 AM"
thats pretty easy. just iterate through the string char by char , build substrings on the fly if the previous char is the same - and the end you'll have a bunch of substrings (maybe a multi-dim array) and just compare the sizes of these.
AABBBBBCCCCDDDEEEEEEEE
$string[0]="AA";
$string[1]="BBBB";
$string[2]="CCCC";
$string[3]="DDD";
etc..
I had to do the swap-2-numbers thing back in 1973 on a PDP-11. I had forgotten the method. As for recursion, it's good for tree population and list containers.
"mtrpcic on February 27, 2007 08:51 AM"
you're wrong. you didnt start at 1
I 'd love to see a COBOL implementation of Fizz Buzz here.
And dont cheat. Code must be runnable with cut-paste. You know what i mean. Mandatory divisions-sections, proper line positioning and stuff.. He he...
Assume the ANSI 85 standard. Anyone?
Matthew,
In your perl version, you could have done this, to be more perlish of course.. (I prefer readability/cleanliness/maintainability, hence I use python).
instead of:
$out .= (($i % 3) == 0) ? "fizz" : "";
you could just use:
$out .= (!($i%3)) ? "fizz" : "";
This response is only to point out the above, I'm not criticising or 'correcting' anything.. just pointing out that in perl as with other languages doing a simple NOT operand removes unnecessary right side evaluation operators. The thing that bothers me still about perl is that in my solution, the ratio of punctuation vs. alphanumerics is greater than 2:1 $.=(!($%))?"":""; : out3fizz
For the guy who wrote the "executable line noise" Perl version: I'm glad you program in Python.
use strict;
use warnings;
for my $i (1..100) {
my $div3 = $i % 3 == 0;
my $div5 = $i % 5 == 0;
if ( $div3 and $div5 ) {
print 'fizzbuzz';
}
elsif ($div3) {
print 'fizz';
}
elsif ($div5) {
print 'buzz';
}
else {
print $i;
}
print "\n";
}
It's not clever, but I'll be able to read it easily 6 months or a year later.
If you insist on the ternary operator, try this:
for my $i (1..100) {
my $div3 = $i % 3 == 0;
my $div5 = $i % 5 == 0;
print +($div3 and $div5) ? 'fizzbuzz' :
$div3 ? 'fizz' :
$div5 ? 'buzz' :
$i;
print "\n";
}
My MS SQL Solution...(im a newbie programmer, so its probably not the most efficent solution!)
declare @i int
declare @text varchar(50)
declare @i3 int
declare @i5 int
set @i=1
while @i <= 1000
begin
set @text = ''
set @i3 = @i/3
set @i5 = @i/5
if (@i3*3=@i) and (@i5*5<>@i)
begin
set @text = 'Fizz'
end
if (@i3*3<>@i) and (@i5*5=@i)
begin
set @text = 'Buzz'
end
if (@i3*3=@i) and (@i5*5=@i)
begin
set @text = 'FizzBuzz'
end
print convert(varchar(5),@i) + ' - ' + @text
set @i = @i + 1
end
Any comments id be grateful - MattConway@GMail.com
Matt Conway on February 27, 2007 9:11 AMMy favorite posters are those who lambast others' fizzbuzz programs, then go post their own incorrect solutions.
Like "mtrpcic" above. Too funny...
Yeah, I can write a Sieve of Eratosthenes, but why are you only sifting out two primes? Well, you ask a silly question, you get a silly answer. We don't even need looping or conditional statements for this one.
print 1
print 2
print "Fizz"
print 4
print "Buzz"
print "Fizz"
print 7
print 8
...etc, etc.
<?php
for ($i=1; $i <= 100; $i++) {
echo $i;
if ($i%3 == 0) {
echo " fizz";
}
if ($i%5 == 0) {
echo " buzz";
}
echo "<br />";
}
?>
netron:
Actually, that's a pretty inefficient way to do it.
Bah, was going to explain, but writing code'll be easier:
public int GetLargestSequence(string input)
{
int largest = count = 1;
char largestChar = input[0];
for (int i = 1; i < input.Length; i++)
{
if (input[i] != input[i - 1])
{
if (count > largest)
{
largest = count;
largestChar = input[i - 1];
}
count = 0;
}
count++;
}
}
Should work anyway, not tested... web forms don't compile well. ;) No need to keep a bunch of string arrays around when you're just counting something.
Telos on February 27, 2007 9:15 AMMy first attempt:
(1..100).each do |i| puts i % 3 == 0 ? (i % 5 == 0 ? "FizzBuzz" : "Fizz") : (i % 5 == 0 ? "Buzz" : i) end
It's ugly, but the whole point was your first non-tested 'on the paper' result :)
mtrpcic: Yeah, it is.. but yours is wrong also since the spec was 1 to 100, not 0 to 99.
Peter Cooper on February 27, 2007 9:16 AMFH wrote: "On recursion, I stand by my advice to students. You should know what it is, how it works, and how to program it. But you should _never_ use it in production code, because whoever maintains it may not grasp what is going on."
"Never" is a bit strong, but think you are closer to right than to wrong on this one. Perhaps in a perfect world everyone would be fluent in recursion, but in the real world you are likely to be causing maintenance problems for all but an elite few if you use it.
More importantly, you are clearly thinking about maintenance issues and teaching to them in class. If your students graduate and find themselves in a situation you didn't cover in class, which they will, then at least their heads will be in the right place to start with.
T.E.D. on February 27, 2007 9:21 AMThe definitive C++ solution:
#include <iostream>
template <int n, int m3, int m5>
struct fizzbuzz
{
fizzbuzz<n-1, (n-1)%3, (n-1)%5> fb;
fizzbuzz()
{ std::cout << n << std::endl; }
};
template <int n>
struct fizzbuzz<n, 0, 0>
{
fizzbuzz<n-1, (n-1)%3, (n-1)%5> fb;
fizzbuzz()
{ std::cout << "FizzBuzz" << std::endl; }
};
template <int n, int p>
struct fizzbuzz<n, 0, p>
{
fizzbuzz<n-1, (n-1)%3, (n-1)%5> fb;
fizzbuzz()
{ std::cout << "Fizz" << std::endl; }
};
template <int n, int p>
struct fizzbuzz<n, p, 0>
{
fizzbuzz<n-1, (n-1)%3, (n-1)%5> fb;
fizzbuzz()
{ std::cout << "Buzz" << std::endl; }
};
template <>
struct fizzbuzz<0,0,0>
{
fizzbuzz()
{ std::cout << 0 << std::endl; }
};
template <int n>
struct fb_run
{
fizzbuzz<n, n%3, n%5> fb;
};
int main()
{
fb_run<100> fb;
}
It may be a bit long.
Emmanuel Deloget on February 27, 2007 9:26 AM@Patrick
>But there's no need to check B - it has no vowel.
You're right. I reread it, and caught myself expanding "one side" and "other side" into an iff scenario.
The original premise is: "one side vowel" -> "other side even"
The only other logically equivalent statement is: "one side not even" -> "other side not vowel" (equivalent to "one side odd" -> "other side consonant")
So, you'd have to check vowels and odds, or "A" and "3"
My original problem with the question still holds though. You have to assume a particular level of precision in writing on the probelm writer. Do they really know the difference between if and iff?
You might be caught on an off day for that sort of a problem. Will you be doing minimal test scenarios yourself all the time with no opportunity to come back when you're feeling "not so dumb"? etc
Uh, someone ordered an x86 assembly version?
(Linux Syscalls/NASM/ELF)
%macro write 2
; Argument 0: char* string to write
; Argument 1: length of string
mov edx, %2 ; edx = length
mov ecx, %1 ; ecx = string
mov ebx, 1 ; ebx = "stdout" stream
mov eax, 4 ; eax = "WRITE"
int 0x80 ; Linux syscall
%endmacro
section .rodata
FIZZ: db "Fizz"
BUZZ: db "Buzz"
NL: db 0xa
section .bss
i: resb 1
c: resb 1
tmp: resb 1
section .text
global _start
_start:
mov byte [i], 1
forloop:
cmp byte [i], 100
jbe not_exit
jmp exit
not_exit:
; if (i % 3 == 0)
mov al, [i]
xor ah, ah
mov cl, 3
div cl
test ah, ah
jnz trybuzz
write FIZZ, 4
; if (i % 5 == 0)
mov al, [i]
mov cl, 5
div cl
test ah, ah
jnz not_buzz
write BUZZ, 4
not_buzz:
jmp continue
trybuzz:
; if (i % 5 == 0)
mov al, [i]
xor ah, ah
mov cl, 5
div cl
test ah, ah
jnz printnum
write BUZZ, 4
jmp continue
printnum:
; Write the number i
mov al, [i]
xor ah, ah
cmp al, 100
jl tens
mov cl, 100
div cl ; ah = al % 100
add al, '0'
mov [c], al
mov [tmp], ah
write c, 1
mov al, [tmp]
xor ah, ah
tens:
mov al, [i]
cmp al, 10
jl ones
mov cl, 10
div cl ; ah = al % 10
add al, '0'
mov [c], al
mov [tmp], ah
write c, 1
mov al, [tmp]
xor ah, ah
ones:
add al, '0'
mov [c], al
write c, 1
continue:
write NL, 1
inc byte [i]
jmp forloop
exit:
mov ebx, 0
mov eax, 1
int 0x80
; OH MY GOD THAT TOOK AGES!!!!!!
Matt Giuca on February 27, 2007 9:32 AMDavid,
Regarding the executable line noise version. It was intentionally ugly. When I professionally worked in perl environments (for about 8 years solid), my perl was quite clean and organised. Were it not for the excessive perl punctuation you might confuse it with clean Java code. I know I could've written it over a series of lines, etc., but that wasn't the point. I'm not a big fan of obfuscated code but in something as simple as the fizzbuzz exercise, I was just pointing out that it can be accomplished in what is essentially one command, not actually a code block. The only reason that the {}'s were included is because it is necessary in a for loop.
And yes, I agree that 3-level deep nested in-line conditionals are ugly and if I ever found any used in production code within our subversion repository, I'd have the person responsible taken out behind the shed and thrashed with a switch.
Eric
Eric Elinow on February 27, 2007 9:33 AMYour tests do indeed screen out people who cannot code without a computer. If part of the job requirement is writing coding without a computer then I guess this is a good test.
Most programmers (myself included) write code on a computer and don't have the visualization skills to program on paper. Whenever I get these questions in an interview I reply that I don't code on paper and if they want an example of my coding, they can give me a problem to solve and a computer to solve it on.
Bob on February 27, 2007 9:33 AMWow, and the elimination of indentation made the whole thing look like garbage!
Matt Giuca on February 27, 2007 9:33 AMR. Butler: There's a typo in the code you refer to (by the original poster of that code).
The actual swap logic uses only XOR:
A = 5
B = 10
A = A XOR B // A == 15, B == 10
B = B XOR A // A == 15, B == 5
A = A XOR B // A == 10, B == 5
As you can see, the swap does occur. :-)
KenW on February 27, 2007 9:34 AM public abstract class Factory
{
public string ToString(char[] chars)
{
return new string(chars);
}
}
public class FizzFactory : Factory
{
private const char F = 'F';
private const char i = 'i';
private const char z = 'z';
public bool isFizz(int input)
{
if (input == 3) return true;
else if (input == 6) return true;
else if (input == 9) return true;
else if (input == 12) return true;
else if (input == 15) return true;
else if (input == 18) return true;
else if (input == 21) return true;
else if (input == 24) return true;
else if (input == 28) return true;
else if (input == 30) return true;
else if (input == 33) return true;
else if (input == 36) return true;
else if (input == 39) return true;
else if (input == 42) return true;
else if (input == 45) return true;
else if (input == 48) return true;
else if (input == 51) return true;
else if (input == 54) return true;
else if (input == 57) return true;
else if (input == 60) return true;
else if (input == 63) return true;
else if (input == 66) return true;
else if (input == 69) return true;
else if (input == 72) return true;
else if (input == 75) return true;
else if (input == 78) return true;
else if (input == 81) return true;
else if (input == 84) return true;
else if (input == 87) return true;
else if (input == 90) return true;
else if (input == 93) return true;
else if (input == 96) return true;
else if (input == 99) return true;
else return false;
}
public string GetFizz()
{
return base.ToString(new char[4] { F, i, z, z });
}
}
public class BuzzFactory : Factory
{
private const char B = 'B';
private const char u = 'u';
private const char z = 'z';
public bool isBuzz(int input)
{
if (input == 5) return true;
else if (input == 10) return true;
else if (input == 15) return true;
else if (input == 20) return true;
else if (input == 25) return true;
else if (input == 30) return true;
else if (input == 35) return true;
else if (input == 40) return true;
else if (input == 45) return true;
else if (input == 50) return true;
else if (input == 55) return true;
else if (input == 60) return true;
else if (input == 65) return true;
else if (input == 70) return true;
else if (input == 75) return true;
else if (input == 80) return true;
else if (input == 85) return true;
else if (input == 90) return true;
else if (input == 95) return true;
else if (input == 100) return true;
else return false;
}
public string GetBuzz()
{
return base.ToString(new char[4] { B, u, z, z });
}
}
public delegate void FizzBuzzWriter(string input);
public class Looper
{
private FizzFactory Fizz;
private BuzzFactory Buzz;
public event FizzBuzzWriter OnFizzBuzz;
public Looper(Factory fizzFact, Factory buzzFact)
{
Fizz = (FizzFactory) fizzFact;
Buzz = (BuzzFactory) buzzFact;
}
public void execute(int start, int finish)
{
for(int i = start; i<=finish; i++)
{
string val = String.Empty;
if (Fizz.isFizz(i)) val += Fizz.GetFizz();
if (Buzz.isBuzz(i)) val += Buzz.GetBuzz();
if (val == String.Empty) val = i.ToString();
if (OnFizzBuzz != null) OnFizzBuzz(val);
}
}
}
public class TheFizzBuzzProgram
{
public static void main(string[] args)
{
Looper l = new Looper(new FizzFactory(), new BuzzFactory());
l.OnFizzBuzz += new FizzBuzzWriter(l_OnFizzBuzz);
l.execute(1,100);
}
static void l_OnFizzBuzz(string input)
{
Console.Write(input + Environment.NewLine);
}
}
I don't believe the 199 out of 200 statement.
My experience as a manager and programmer is that
only a very few candidates can't program.
I've had exactly one instance in interveiwing
about 200 people over the years where the person
said they knew SQL and when I asked them to write a simple
SELECT statement on the board, they admitted they didn't know
SQL *that* well.
Now I have seen lots of programmers that simply were very poor programmers. It is rare to find a self motivated, can-do type of programmer that comes up with a good solution without any coaching.
rkeene on February 27, 2007 9:41 AMI like FizzBuzz, though there's something to be said for jumping straight to a pointer/recursion screening question.
I'm not so fond of the "swap two variables without using a temporary variable" question. There's several possible outcomes of asking it.
1) The candidate can answer the question correctly:
1a) ...because the candidate has seen the trick before. Chance of hiring: Unchanged, because we've learned nothing useful.
1b) ...because the candidate has enough mathematical sophistication to solve the problem from scratch. (All you need is an algebra with a binary operator and inverse elements[1].) Chance of hiring: Increased.
2) The candidate can't answer the question correctly:
2a) ...because the candidate is a poor programmer. Chance of hiring: Decreased.
2b) ...because the candidate is a good programmer who doesn't see the trick, and isn't quite clever enough to derive it from first principles. Chance of hiring: Increased (for most jobs).
The scoring matrix is all screwy here: Some bad candidates answer the question well (a subset of 1a), and some potentially good candidates miss it (2b). Now, you could argue that for some jobs (say, programming at Google), you don't mind losing the competent but mathematically weak programmers in group 2b. In that case, the scoring matrix is a little better, but it still doesn't distinguish between group 1a and group 1b.
If you really want to hire exclusively from group 1b, you'd get better results by asking a straight-out math question.
[1] The inverse elements allow you to rewrite "b=a-b" as "b=(-b)+a", which gets rid of the compiler-allocated temporary variable that some architectures require for "b=a-b". Of course, signed C integers aren't closed under addition, so you're better off using xor for this trick.
emk on February 27, 2007 9:45 AMIt's not "can you program in X language" but "Can you program in ANY language" or even a psuedocode that is reasonably similar to the target language?
If the target language is C, don't fault a guy who hasn't touched C in 3 years and forgot the syntax of a for loop. If he can show you he knows the key concepts of programming in a procedural language don't reject him out of hand.
If the target language is Prolog or LISP, knowing ONLY C or another procedural language may not be a lot of help.
Two exceptions: If you need him to be pumping out code at full speed in the first 2 days, you need someone who really knows the language now. If you need full speed within a week, you know someone who really knew the language at one time. With anyone else, give them a couple weeks and they'll be up to speed.
davidwr on February 27, 2007 9:46 AMThis post is like making a comment on a Star Trek forum about the guy in the yellow shirt that dies on the away mission.
Steve Steiner on February 27, 2007 9:46 AMAlright, well, as a current computer science major with 8 years real work experience under my belt, I can tell you this: People are persistent. They're just not willing to admit they cannot do something. Often times this means some CS majors spend 40 hours on simple 100-200 level projects... and pass the class. You'd think the theory would weed them out, but let's face it, college is geared towards those who study for the test. After the test is complete, who cares, right? "I'll never see recursion again!"... uh... no. I'm actually astonished how many of your commentators have already said they don't use it. Some have gone so far as to say that even if you do understand recursion and it makes the best code, it's better not to use it for the sake of the idiot they hire to maintain your code...
... What the hell? I'm a web developer and I use recursion a great deal, and in ways most people wouldn't consider. I understand that it can actually be a performance hog many times, but if you have a deep underlying knowledge of how the server handles memory, this shouldn't be a problem.
Where is the respect for our trade? Do we really want to cater software development to the lowest common denominator of coders? Every single test I've taken to land a job has been so easy it made me insulted they asked. I decided to take an internship this past summer, for example. In one of my interviews (as a web developer for the Tools department of AOL), they tested me to ensure I knew that GET and POST existed... not when to use them... not how to use them... not even what they were. They just wanted to know if I knew they existed.
As a web developer, I almost assume any applicant would know this just by applying for the job.
I didn't take that job. That kind of question almost guarantees bitch work. Instead I went with the interviewer who asked me questions I didnt know... like what port is used for DNS UDP. And sure enough, that job gave me more freedom, and plenty of good honest to god work experience. I talked to the intern from tools, and yeah, bitch work. In fact, I received 4 internship offers from AOL that summer and two job offers which I turned down... more than any other intern there to my knowledge. And what's my college GPA?
...
...
2.10
Yeah, I'm not doing so hot in school. Why? I can't really give a good excuse. Laziness is my only reason. I can't seem to drag myself to attend a class I can just as easily teach myself in a matter of days yet somehow takes our class an entire semester and people still do not get it.
Some people, such as my roomate right now, will graduate with near 4.0 GPA's and will not be expert programmers. What a waste of 4 years, if you ask me.
Rafajafar on February 27, 2007 9:46 AMKris, you didn't read the requirements, x is not printed if anything else is. Understand the requirements.
zetaprime on February 27, 2007 9:47 AMI wrote this in C++ ....it compile right and seemed output to the screen correctly. I'm no computer programmer, I just fiddle around with stuff.
I timed myself it took 25 to 30 minutes.
#include <iostream>
using namespace std;
int main()
{
int counter = 1;
int three;
int five;
while(counter < 101)
{
three = counter % 3;
five = counter % 5;
if(three == 0 && five == 0)
{
cout << "FizzBuzz" << endl;
}
if (three != 0 && five != 0)
{
cout << counter << endl;
}
if (three == 0 && five != 0)
{
cout << "Fizz" << endl;
}
if (three != 0 && five == 0)
{
cout << "Buzz" << endl;
}
counter++;
}
system("PAUSE");
}
Why the hostility to these questions?
They are quite appropriate if you accept a variety of answers; I would take anything that showed the ability and inclination to think.
I would expect them to to get the Fizzbuzz problem logically correct, but not worry too much about syntactic details.
I would happily accept "Hmm. I'm not sure how to swap two integers in place, but I bet there is some sort of bitwise trickery that can be used".
If I asked someone to write a recursive implementation of (say) the Fibonacci sequence, I would expect them to be able to pull it off-- but I would be overjoyed if they said "You know, this degenrates into a O(2^n) problem when implemented recursively due to recalculation. It would be better to implement it iteratively. Or if you insist on recursion, you could get O(n) time by using memoization".
THAT is why you ask these questions. To find the people who can solve problems and propose solutions that you hadn't foreseen. Sure, there is a place for code monkeys who can grab values from a form and stuff them in a database. But I will MAKE a place for a programmer with insight, problem solving skills and a genuine love of their craft.
Silas on February 27, 2007 9:54 AMgcc actually compiles more efficient code when using a temp variable than it does if you use the xor trick.
--- swap.s Sun Feb 25 02:06:34 2007
+++ xor-swap.s Sun Feb 25 02:05:52 2007
@@ -24,9 +24,12 @@
call gets
movl %eax, (%esp)
call atoi
+ orl %eax, %ebx
addl $12, %esp
- pushl %ebx
+ xorl %ebx, %eax
pushl %eax
+ xorl %eax, %ebx
+ pushl %ebx
pushl $.LC0
call printf
leal -8(%ebp), %esp
The xor thing is one little antique trick which is completely and utterly pointless to ask about in an interview.
Stewie on February 27, 2007 9:55 AMThe fizzbuzz test requires basic programming knowledge of loops, which anyone with a CS degree should be able to do. The Modulus operator would probably be missed by very new programmers, but you could still write the loop and test the condition with more code without using the modulus operator, although with a code review, this code would be optimized to use less lines with the modulus.
I am not sure if a programming test is the best test to give a developer. If one does give a test, it should be only used to gauge overall level of expertise, not as the sole basis of hiring.
Today's programming world is a vast expanse of knowledge, just the .Net Framework contains 100s to 1000s of classes.
At a previous employer, I made a quiz for C# becuase we needed people who had programmed in C#. It had some questions on the language (framework and Object Oriented questions) as well as a few coding questions.
For example, spot the error
if (a = b)
{
//Do Something
}
Nothing too hard (I don't think), but it was comprehensive enough to week out the people with very little experience which is what it was designed to do.
The final question was a coding test that was very simple:
Write a method to add two numbers together.
When I looked at the test results, usually I would get back something like this:
public int add(int a, int b)
{
return a+b;
}
Now, this works *most* of the time, but usually what I would do is to engage the candidate and ask them the following after they had provided the answer:
What happens if you add int.MaxValue + 1?
Now the "test" is more of an interaction between me and the candidate and it becomes more interactive. After some back and forth, the final question was:
How would you write a program to add any 2 numbers regardless of size? At this point, it is no longer a programming exercise but becomes more of problem solving exercise.
I wanted to see how the candidates would act and problem solve, and how they would respond, if they would ask questions about the exercise, etc. Something as simple as adding 2 numbers together can tell you alot about a person's programming and problem solving skill.
The side topic of recursion....
Recursion is usually illustrated by the Tower of Hanoi problem. Usually you have to move 8 disks from one pole to another. The exercise I did was for C++ a few years back and it worked great to move 8 or so disks. Then I tried 20 and 100. You know what happened? Stack overflow!
Now, just by experimenting with more disks I broke the program. Additionally, I learned that any any recursive code can be solved iteratively. So, this changed my outlook on recursion in general.
Recursion is very clever which produces a solution with very few lines of code, but try debugging it when there is a problem. Nightmare.
Clever works in academic environments, but I'll take maintainable and supportable over clever any day. Plus, recursion is destined to fail at a certain amount of iterations because there is only so much space on the stack.
Coming to Theater in 2008 - Toy Story 4 - Buzz Lightyear and the attack of the FizzBuzzers.
I took me 4 minutes to write the working code in PL/SQL. But I am not a programmer, just a DBA.
I wanted to test myself to he how good or bad I am.
What do you have to be afraid of - failure?
michael on February 27, 2007 9:57 AMOverall this doesn't surprise me too much.
It's amusing that various answers seem to indicate the writer didn't actually read the question. Well, I assume that if you dare to comment with code you solved your *understanding* correctly, anyhow...
I'm not sure how fair the FizzBuzz test is, not because of the test, but because it is written. I always hated having to write code on exams (especially without scratch paper) because when you type code, as one always does, you can instantly spot spot mistakes, convoluted logic (I sometimes annoy friends by simplifying their logic into a fraction of its original size), easily redundant code (and unnecessary expensive instructions -- don't you know modulos are dozens of clocks, people?), you can restructure typed code, throw evaluations into or out of loops in seconds.
Not only that, you have brain left over to run all sorts of simple heuristic checks out, visual checks (I'm elsing that? duuuuh, get more coffee!) be it out of experience or a bordom of sorts.
But mostly there's just the extra hurdle to paper. You are suddenly required to to keep several complete solutions in your head before you even put pen to paper. Because I have my pride - I'm not going to give you a stupid solution.
I much, much prefer even notepad to paper. I think many would agree, especially when he logic to be worked out involves several not-completely-trivivial bits. Fizzbuzz really only has one, some exclusiveness you need to consider.
scarfboy on February 27, 2007 9:59 AMNick Franceschina, you rock dude. Made me laugh so hard :D
cwiz on February 27, 2007 10:03 AMWow, Look at all the different languages people have used to do the Fizz Buzz and some have done it poorly. Does it still make them eligible for the job? And this is when the blog(post) by Jeff wasn't even about writing the solution. :)
Kashif Razzaqui on February 27, 2007 10:07 AMI'm so amazed that *graduates* actually fail these miserable tests when the skill level required to hold a programming job is usually so beneath that of a compsci degree -- That is, once you learn a programming language that's actually marketable and get going with the productivity imperative. Should we conclude that the market is saturated with pretenders applying for every computing job around? I wonder why don't they postulate for sales job, instead, where salaries are attractive and pretending can actually be a plus. Hm, I might be getting a bit cynical here... Sorry 'bout that.
To me, these "observations" sound more like a war stories than anything else. The kind told by disenchanted employers wishing for affordable "plug'n play" elite programmers they haven't found; or by proud, devoted application developers in need of shock therapy.
I would have thought that the world was plenty with decent programmers who could do very decent work within somewhat decent working environments. Otherwise, finding good work wouldn't be such a hassle. Perhaps there's a mismatch in the way employers and job applicants are looking for each other... Judging by the various ways each of us answered to this post, it's clear that we don't all agree about what makes a good programmer for hire. It seems to depend on the job and, mostly, on our own background and perceptions.
In my case, my personal best bet would be to set up a nice working environment, hire bright enough people and let them grow. Since our profession is being mostly about shifting our understanding from the consumer to the machine, from architecture and logic to technology and implementation, I would rather build a team with complementary skills rather than give a job to every member of the LISP club who has already built a compiler. There's more than one way to be a good programmer.
stochastio on February 27, 2007 10:07 AMI can unfortunately say that this applies to all of engineering, not just software. I work in embedded control systems where a lot of Mechanical types end up, and most of the candidates we interview end up knowing nothing of either discipline. I've met guys with graduate degrees from serious big name schools who can't solve some really pathetic problems.
The real lesson here is that how a person looks on paper will rarely reflect their actual abilities.
Dan on February 27, 2007 10:10 AM(Wonder who's going to read this far...?)
Need a requirements clarification (seems like Mr Dieterich was the only one that picked this up!?)
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”.
Should the last requirement be:
'.... *instead* print "FizzBuzz".'
or
'.... *also* print "FizzBuzz".'
?
Actually I got asked a really simple question the last interview I had: given two rectangles in space, how do you test whether they overlap? I faltered for a moment, and remarked that I'd never actually done that before and had no idea how to do it. Then I got a piece of paper and did it. Really easy of course, but I think the interviewers got more information out of that than if I had automatically known how to do it.
Anyway, FizzBuzz is an ideal problem in which to be clever and use goto!
Sorry I can't resist.
for(int i = 1; i <= 100; ++i)
{
if(i % 3 == 0) { std::cout << "Fizz"; goto fizzbuzz_newline; }
if(i % 5 == 0) { std::cout << "Buzz"; goto fizzbuzz_newline; }
std::cout << i;
fizzbuzz_newline:
std::cout << endl;
}
Unless you want the object-oriented C++ version:
http://interreality.org/~reed/tmp/fb.cc
AndyToo wrote:
"I've been making a decent living from programming for over ten years, and if I may say so, I write some damn good code."
and 90% of people who say they're good programmers are actually horrible. :)
no offense, but if you've never had to use recursion in 10 years of "programming," then i highly doubt your solutions are optimal... heck i'm just a lowly front-end programmer and i definitely have to use recursion from time to time.
nabby on February 27, 2007 10:12 AMChris, I'm with you on being wary of the precision of the writer in a lot of questions. I always wanted to argue with the multiple-choice authors when I was back in school.
That's why I like that song that goes:
"I can't see me loving nobody but you for all my life"
Just how precise is that?
Patrick on February 27, 2007 10:13 AMIt's funny to see some of the solutions. I am in no means a "hard core" programmer (I didn't know if VB had a MOD function since I haven't used that since I did Pascal back in college). But it's one of those tests that is so simply you have a chance not to follow the directions.
This took me about a minute to write, if I had more time I would have found out if MOD was better to use. But it covers the requirements: 1) Loop 1 to 100, 2) print FizzBuzz every 15, 3) print Buzz every 5 and 4) print Fizz every 3.
And I would have asked the clarification if they supercede each other or if you would need to print Fizz Buzz FizzBuzz every 15.
Sorry Jeff for posting a solution, but if you can memorize something like this for a job interview, then you can write a loop anyway.
<CODE>
'VB6
Const fizz = 3
Const buzz = 5
Const loopEnd = 100
Dim x
For x = 1 To loopEnd
If x / (fizz * buzz) = Round(x / (fizz * buzz), 0) Then
Debug.Print "FizzBuzz"
ElseIf x / buzz = Round(x / buzz, 0) Then
Debug.Print "buzz"
ElseIf x / fizz = Round(x / fizz, 0) Then
Debug.Print "Fizz"
Else
Debug.Print x
End If
Next
</CODE>
I say, all the fucking better. The more shitty programmers there are out there in the world, the more in-demand us programmers that can actually think are. I say, let 99% of the programmers be dullards, so they can pay their salaries to me!
By the way, that algorithm can be written in like 9 lines:
for( int i=1; i<101; i++ )
if( i % 3 == 0 && i % 5 == 0 )
System.out.println( "FizzBuzz" );
else if( i % 3 == 0 )
System.out.println( "Fizz" );
else if( i % 5 == 0 )
System.out.println( "Buzz" );
else
System.out.println( i );
DONE! Java > all.
Nick Franceschina's solution is nearly perfect. The only thing that is needed is to put the isBuzz and isFizz methods behind some webservice calls, then it's the perfect solution. Concise AND flexible. ;)
Joe on February 27, 2007 10:19 AMI do not know of anyone in my Computer Science graduating class that could not write a version of this in java/c++ and at least one other language in under 5 minutes.
Who are you interviewing, and how are they getting these interviews?
for (int i=1; i <= 100; i++) {
Console.WriteLine(new object[] { "FizzBuzz", "Fizz", "Buzz", i}
["033132133123133"[i % 15]-'0']);
}
couldn't help myself, a one liner in php
while($a<101){ echo (($a%3)!=0) ? $a."\n" : "Fizz\n"; $a++;}
Cheers
i'm a professional (web) developer, often changing between php, classic asp, vba, vb.net/c#.net, sql, javascript, html, etc., etc. we do customizations to sites that have been written already.
the thing is, if you asked me to write a for loop from 1 to 10, i may get it syntactically wrong if i've been coding in a different language recently.
so, to me, i think asking people to code at an interview isn't necessarily a great assessment of their ability.
Thimble on February 27, 2007 10:27 AMfor (int i=1; i <= 100; i++) {
Console.WriteLine(new object[] { "FizzBuzz", "Fizz", "Buzz", i}
["033132133123133"[i % 15]-'0']);
}
Sadly, the "can't write FizzBuzz" guys end up being promoted more often than not too.
The realities of the modern work place is that it's more important for a programmer to be able to update his milestones in Microsoft Project and draw his designs in Visio that exports to PowerPoint than to actually deliver on his milestones.
JMXZ on February 27, 2007 10:31 AMThere is very much truth to what you said. Don't know about the "statistics" you present, but real-world proficiency seems to be a problem in many fields. In any case, here's my two cents in about three minutes (not the only way, I know). It is HTML for the purpose of presenting HTML (hence the commented code):
<!--
<html>
<head>
</head>
<script>
for (i = 1; i <= 100; i++) {
switch (i%15){
case 0:
document.writeln("FizzBuzz<br/>");
break;
case 5:
document.writeln("Buzz<br/>");
break;
case 10:
document.writeln("Buzz<br/>");
break;
case 3:
document.writeln("Fizz<br/>");
break;
case 6:
document.writeln("Fizz<br/>");
break;
case 9:
document.writeln("Fizz<br/>");
break;
case 12:
document.writeln("Fizz<br/>");
break;
default:
document.writeln(i + "<br/>");
break;
}
}
</script>
</html>
-->
Thanks for the observations and insight :)
Peter on February 27, 2007 10:34 AMOh, boy. You write an insightful post and we all jump on the code quiz. You knew someone would have to write this in MSIL, right?
.assembly extern mscorlib {}
.assembly fizzbuzz {.ver 1:0:1:0}
.module fizzbuzz.exe
.method static void main() cil managed
{
.entrypoint
.maxstack 2
.locals init (
[0] int32 num,
[1] bool divisibleByThree,
[2] bool divisibleByFive)
//initialize counter
ldc.i4.1
stloc.0
br.s _checkEndCondition
_beginLoop:
//Check divisible by three
ldloc.0
ldc.i4.3
rem
ldc.i4.0
ceq
stloc.1
//Check divisible by five
ldloc.0
ldc.i4.5
rem
ldc.i4.0
ceq
stloc.2
//Check if not divisible by three or five
ldloc.1
brtrue.s _checkDivisibleByThree
ldloc.2
brtrue.s _checkDivisibleByThree
//Not divisible by three or five, write counter
ldloc.0
call void [mscorlib]System.Console::WriteLine(int32)
br.s _incrementCounter
_checkDivisibleByThree:
ldloc.1
brfalse.s _checkDivisibleByFive
ldstr "Fizz"
call void [mscorlib]System.Console::Write(string)
_checkDivisibleByFive:
ldloc.2
brfalse.s _newLine
ldstr "Buzz"
call void [mscorlib]System.Console::Write(string)
_newLine:
call void [mscorlib]System.Console::WriteLine()
_incrementCounter:
ldloc.0
ldc.i4.1
add
stloc.0
_checkEndCondition: ldloc.0
ldc.i4.s 0x65
blt.s _beginLoop
ret
}
I'm lame for even posting this...
Java. 5 min. Including testing. For production code I'd bother with comments and even a lame test case. Suck on it.
public class FB {
public static void main(String [] args){
for(int i = 1; i <= 100 ; i++){
String out = "";
if(i % 3 == 0){
out = "Fizz";
}
if( i % 5 == 0){
out += "Buzz";
}
if(out.length() > 0){
System.out.println( out);
}else{
System.out.println(i);
}
}
}
}
Obviously is so many people do not answer this, then there might be something wrong with the question.
I have been in interviews where some monkey asks me to find syntax bugs by hand...what the hell is the IDE for ! You might as well give a professional author a spelling quiz (what, you never heard of a spell checker!)
I get tasked this kind of stuff during an interview these days I just leave. It is a waste of my time. The last kind of place I want to work it is one where I am asked to write menial pieces of code at a moments notice without any planning or forethought and have someone look over my shoulder the whole time. And I certainly don't want to work with techhie freaks who only think about code syntax and the penis sizes of various star wars characters all day long
Yes, I have a PHD, developing hard core quantum meahnics simulation code. Yes, I have managed and coded commercial products that are in the market.
If you want to ask someone to do some work, then you should simulate the work environment. Let them bring in their environment, a laptop, hook them up to the internet so they have access to all of their resources. Tell them what you are going to be discussing so they can review what they need to know. Give them some time to think about what is going on? Then ask them to do something non-trivial which actually reflects the job they are being interviewed for.
Beleive it or butt munches, not everyone spends their free time memorizing the java syntax or solving high school puzzles.
More importantly and most accurately, not every stores and processes information in their mind in the same way.
I program all day every single day. That does not mean I will be able to recall the information at a momments notice or have the interest in writing code on the blackboard during a conversation. I simply don't store and process the information that way--oh, and chance are, I don't really want to spend my days talking to geeks all day long about trivial things.
Have any of you little nerds every played a sport? Have you tried to
do a back flip or hit a ball when someone is talking to you? For god's sake, go get a damn book on how the brain stores and processes and retrieves information.
Learn how to interview for the job, not your ego!
Chalres H Martin on February 27, 2007 10:37 AM1. After f in hex comes 10.
2. Swap two variables (regardless of type)
list($b, $a) = array($a, $b);
3. Fizzbuzz in PHP:
foreach (range(1,100) as $i) {
if (!($i % 3)) $o = 'Fizz';
if (!($i % 5)) $o .= 'Buzz';
if (!$o) $o = $i;
echo $o . "\n";
unset($o);
}
Do I get the job? ;-)
Douglas Clifton on February 27, 2007 10:39 AMYes this is sad, but I had to type it up...
class Program
{
private const string Fizz = "Fizz";
private const string Buzz = "Buzz";
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
bool bMultipleOf3 = (i % 3 == 0);
bool bMultipleOf5 = (i % 5 == 0);
if (bMultipleOf3)
{
Console.Write(Fizz);
}
if (bMultipleOf5)
{
Console.Write(Buzz);
}
if (!(bMultipleOf3 || bMultipleOf5))
{
Console.Write(i);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
Ha! I dropped out of CS in my third year to go into the clergy, and 13 years later I still was able to write FizzBuzz in C++ in about 4 minutes. Now for the real prize: CAN ANYONE WRITE IT IN ASSEMBLY?
Peter on February 27, 2007 10:42 AMWhile you guys were so busy frantically coding solutions to the FizzBuzz problem, you might've stopped for a moment to consider whether you were going to get owned by the > and < tags.
I fixed all the code samples with angle bracket problems. But be sure to check out my followup *BEFORE* submitting any more code in the comments, please. (although some of them were quite funny, and for that, I salute you)
http://www.codinghorror.com/blog/archives/000804.html
> Has anyone thought of creating a web page where we can see cross-language solutions to the FizzBuzz problem? Once there are enough solutions (and optimizations) posted, perhaps it can be spun off into the Great FizzBuzz Programming Shootout. And don't forget a job board and forums to connect with prospective employers. This is an exciting time to be in software development.
http://golf.shinh.org/p.rb?FizzBuzz
My friend, the internet is your huckleberry. The FizzBuzz programming competition in any language of your choice.
Jeff Atwood on February 28, 2007 12:23 AMLame. That golf.shinh.org thing accepts the whitespace language, but not MSIL? Lame, lame, lame!
Jon Galloway on February 28, 2007 12:30 AMI totally agree .... I refer you to my blog post above on just the same subject ...
Casey on February 28, 2007 12:39 AMI mainly program in Visual Basic.
My solution for the FizzBuzz question would be:
Option Explicit
Private Sub Form_Load()
Dim intCount As Integer
Dim blnFizzBuzz As Boolean
For intCount = 1 To 100
If int_Teller Mod 3 = 0 Then
txtResult.Text = txtResult.Text & "Fizz"
blnFizzBuzz = True
End If
If intCount Mod 5 = 0 Then
txtResult.Text = txtResult.Text & "Buzz"
blnFizzBuzz = True
End If
If Not blnFizzBuzz Then
txtResult.Text = txtResult.Text & int_Teller
End If
txtResult.Text = txtResult.Text & vbCrLf
blnFizzBuzz = False
Next intCount
End Sub
To swap two strings without temp var I'd use this:
Dim String1 As String
Dim String2 As String
String1 = String1 & String2
String2 = Left(String1, Len(String1) - Len(String2))
String1 = Right(String1, Len(String1) - Len(String2))
I guess we're all somehow work enslaved idiots ;) posting these solutions here because that never was the question.
Leo on February 28, 2007 12:46 AMYou should all go see http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html
to see the difference in programmers.
My productivity question lies elsewhere. Can you work for 1 day without a mouse? Try it and see the horror on the users' faces. Practice it and see the increase in productivity.
chris on February 28, 2007 12:48 AMOops! forgot to change a var int_Teller to intCount
Shame on me! I failed the test...
Yay!
Five minutes. (*Whew!*) My first one ever :)
Here is my code to produce my solution:
#include <stdio.h>
int main(void)
{
printf("#include <stdio.h>\nint main(void)\n{\n");
int i;
for (i = 1; i <= 100; i++)
{
printf("\tprintf(\"");
if (i % 3 == 0 && i % 5 == 0)
printf("FizzBuzz");
else if (i % 3 == 0)
printf("Fizz");
else if (i % 5 == 0)
printf("Buzz");
else
printf("%d", i);
printf("\");\n");
}
printf("\treturn 0;\n}\n");
return 0;
}
After 10 years writing C in low power embedded systems, including a fair bit of interviewing, what seems more interesting than asking candidates for a solution to a given problem is to explore their reasoning while arriving at the solution.
Oh, and VB isn't a programming language.
Toby on February 28, 2007 1:09 AMVB isn't a programming language? Neither is C. C is for girls. Why don't you write in pure machine language like the rest of us men?
Thanks Alan B, I wish there were more girls using C, it would make the office a much more interesting place to be. Why not use pure machine language? It's not portable and any company that wrote a significant portion of it's product like that wouldn't exist for long.
Naturally VB has its place but interviewing for C (or even assembly coding) jobs is so much more fun as there are so many more subtle issues to discuss than in highly abstract languages. For example above many posters have made statements about 'inefficient code', but nowhere in the design was efficiency stated as a requirement.
Toby on February 28, 2007 1:26 AMTo have something extravagant ...
#_SET:A=[1..100]#
#_FOREACH:A=LINE#
#_BEGIN_DELETE_IFNOT:LINE%3==0#FIZZ#_END_DELETE_IFNOT##_BEGIN_DELETE_IFNOT:LINE%5==0#BUZZ#_END_DELETE_IFNOT##_BEGIN_DELETE_IF:LINE%3==0||LINE%5==0##LINE##_END_DELETE_IF#
#_ENDFOREACH#
:)
Hinek on February 28, 2007 1:31 AMSorry, syntax error ... should be:
#_BEGIN_FOREACH ... _END_FOREACH#
Erm.. why would I want to Fizz my Buzz with a FizzBuzz?
I agree with the article, I think there are too many people out there who don't know how to write code in their head..
But..
That doesn't make them a bad coder or designer to be apt. Coding has become so abstract that most modern coders tend to be designers due to working with heavily gui based apps from Windows form coding to Web apps. So we could blame MS for doing this, but its not really their fault.
The days of the lone coder are gone, most if not all coders have no need to learn or retain any of the stuff they get taught in their college/uni and certainly its not a requirement in a job.
However I think coding should be about architecting a solution and that means working from the ground up. A good coder is someone who has knowledge of each area they are interacting with, not necessarily deep knowledge of a technical component but enough of an understanding to appreciate how their solution will fit into the wider picture.
Coding should be about elegance. It should be like designing a really well made web page that employs lush CSS and is a visual treat to look at. Code should be the same, well commented and fluid in its layout making the code appealing to read.
I have come across too many coders who simply code out of need, usually to meet out of proportion expectations resulting in badly formed code or a solution that has far too many shortcuts in place.
Each to their own though, every problem has a particular solution however I think what this article was touching on was the fact that the core foundation skills of a coder are not present in most interview cases and this is worrying but I think a growing trend.
When you have hand-holding applications like Visual Studio.NET there is no real need to retain information as you can for the most part, cut and paste your way to a solution. :P
Adios,
T
Tahir on February 28, 2007 1:34 AM"Oh, and VB isn't a programming language."
This monkey does not even know that VB was a huge success for MS.
It is the most successful and productive language alongwith Java. I wonder if anyone uses C for application programming.
What is funny to me is how the majority of people who wrote there code on here did the fizz/buzz portion correctly but forgot to print the numbers to screen for the rest.
Maybe the programming world just needs a little attention to detail instilled in them.
You should put up a stat on how many people actually tried to post the code on here and how many of them got it correct!...
Mushoo
Jeff, give a programmer a clear spec, and they'll do it! It's no wonder so many people immediatley started tapping away and created their solutions!
It when real world specifications get handed to programmers and the programmers have to spend 80% of the project time getting the specification clarified.
Very easy in C#:
private void FizzBuzz() {
string fizz;
string buzz;
for (int i = 1; i <= 100; i++) {
fizz = null; buzz = null;
if (i % 3 == 0) {
fizz = "Fizz";
}
if (i % 5 == 0) {
buzz = "Buzz";
}
if (fizz != null || buzz != null) {
Console.WriteLine(fizz + buzz);
}
else {
Console.WriteLine(i.ToString());
}
}
}
Surely this is a test about reading the question (i.e. outputting the numbers)
and efficiency, minimising the number of conditional tests.
So the mod3 mod5 elegant solution misses the non replaced numbers and does 2 conditional checks per loop
This is better:
while(i++ && i<=100)
{
if(i%3)//most likely so first
write("Fizz")
if((i%5))//next likely
write("Fizz")
else if (i%5))//next likely
write("Fizz")
else
write(i)
}
even with this for a non replaced number all 3 conditions are checked first
Peter Stone on February 28, 2007 2:17 AMWriting a program that satisfies your FizzBuzz specification is trivial in any language. The solve the specification you can simply write out the precomputed solution:
println("1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz ...");
This gives you also the best runtime performance ...
Alex on February 28, 2007 2:32 AMThe quality of a good programmer is the ability to know how to beg borrow and steal the right code - AND when not to try and solve a problem from scratch.
Interview of two candidates
Q Write a class to put these items in a linked list.
Candidate 1 Wrote a nice linked list class and used it - failed
Candidate 2 Derived class from a library linked list class, and used sample code - Got job and went down to pub to celebrate!
Having interviewed many so called developers I have come to the conclusion that programming is not necessarily judged *just* on technical skill, but on aptitude.
If an interviewee can show understanding of loops\variables\recursion in pseudo code, they can be taught the implementation in a given language in a few sessions - I normally take time out to teach any new developer coding standards anyway.
Have enjoyed seeing FizzBuzz in obscure languages, here's my contribution in VFP\Foxpro code:
FOR intLoop = 1 TO 100
? IIF(MOD(intLoop,15)=0,"FizzBuzz", ;
IIF(MOD(intLoop,5)=0,"Buzz", ;
IIF(MOD(intLoop,3)=0,"Fizz", ;
intLoop)))
NEXT
//define your own output method with TRACE
void fizzbuzz(int i = 1)
{
if (i > 100) return;
(i%15)?(i%3)?(i%5)?TRACE("%d",i):TRACE("Buzz"):TRACE("Fizz"):TRACE("FizzBuzz");
TRACE("\n");
fizzbuzz(++i);
}
void main()
{
fizzbuzz();
}
//yep, I know this kinf of code is a nightmare for thos who will mantain this code later ;)
Nick Franceschina,the very best:))))
Cira on February 28, 2007 2:57 AMDim i As Integer = 1
Dim newline = False
For i = 1 To 100
Response.Write("<br/>")
If (i Mod 3 = 0) Then
Response.Write("Fizz")
End If
If (i Mod 5 = 0) Then
Response.Write("Buzz")
ElseIf (i Mod 3 <> 0 And i Mod 5 <> 0) Then
Response.Write(i)
End If
Next
End Sub
My version starts with "copy con fizzbuzz.com" but it doesn't seem to be x-platform, so I'll refrain from posting it.
Gabri van Lee on February 28, 2007 3:32 AMI still liked my version in C using one mod operation (i % 15) and a switch statement instead of ifs and elses.
Brendan Dowling on February 28, 2007 3:34 AM for (int i=0;i<101 ;i++)
{
System.out.println((i%3==0)?((i%5==0)?"fizzbuzz":"fizz"):(i%5==0)?"buzz":i+"");
}
programmers are idiots.
PHP:
while(++$i<101) {
if(!($i%15)) echo "FizzBuzz\n";
else if(!($i%3)) echo "Fizz\n";
else if(!($i%5)) echo "Buzz\n";
else echo "$i\n"
}
Unfortunately, no HTML seemingly means no XSLT... tsss.
This program should be run on itself ;-) and of course the square brackets shouldn't be more angular. let's hope this passes the filter then...
[?xml version="1.0" encoding="utf-8"?]
[xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"]
[xsl:output method="text"/]
[xsl:template name="fizzbuzz" match="/"]
[xsl:param name="n" select="1"/]
[xsl:param name="maxN" select="100"/]
[xsl:choose]
[xsl:when test ="$n mod 15 = 0"]FizzBuzz[/xsl:when]
[xsl:when test ="$n mod 5 = 0"]Buzz[/xsl:when]
[xsl:when test ="$n mod 3 = 0"]Fizz[/xsl:when]
[xsl:otherwise]
[xsl:value-of select="$n"/]
[/xsl:otherwise]
[/xsl:choose]
[xsl:text]
[/xsl:text]
[xsl:if test="$n < $maxN"]
[xsl:call-template name="fizzbuzz"]
[xsl:with-param name="n" select="$n + 1"/]
[/xsl:call-template]
[/xsl:if]
[/xsl:template]
[/xsl:stylesheet]
"At Vertigo, we require a code sample before we even proceed to the phone interview stage."
I think that is a great idea !
The only thing better would be if the company was required to provide code samples to the interviewee .. you know, at a later stage in the process, perhaps right before offering a position.
One of the things I hate the most is going through an interview where I am grilled on the most obscure nuances of a language, the type of things you almost never encounter, only to find out after accepting the position that the developers at the company do NOT follow in reality what they preach in the interview.
David on February 28, 2007 3:54 AMChris:
My productivity question lies elsewhere. Can you work for 1 day without a mouse? Try it and see the horror on the users' faces. Practice it and see the increase in productivity.
Working without a mouse is a very unrealistic requirement. Unless your workplace is really out in the sticks, there is no real reason to go without a mouse for more than an hour.
Brady Kelly on February 28, 2007 4:00 AMWelcome to school :)
For the VBScripters that were arguing over carriage returns, a CSscript solution in about 30 seconds:
Dim i
For i = 1 to 100
If i mod 3 = 0 Then WScript.StdOut.Write "Fizz"
If i mod 5 = 0 Then WScript.StdOut.Write "Buzz"
If CBool(i mod 3) And CBool(i Mod 5) Then WScript.StdOut.Write i
WScript.Echo ""
Next
Next we use VBScript to do it in ASP (ok, this is cheating :P ):
<%
Option Explicit
Dim i
For i = 1 to 100
If i mod 3 = 0 Then Response.Write "Fizz"
If i mod 5 = 0 Then Response.Write "Buzz"
If CBool(i mod 3) And CBool(i Mod 5) Then Response.Write i
Response.Write "<br/>"
Next
%>
Then something else...python?
a = []
for i in range(1,101):
a.append((i%15==0) and "FizzBuzz" or ((i%5==0) and "Buzz" or ((i%3==0) and "Fizz" or str(i))))
print a
Damn, time to take a shower and go to work. I think I just wasted most of my morning reading the other replies before I spent a couple minutes writing those three :P
Tarwn on February 28, 2007 4:03 AMAnother C# solution:
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 || i % 5 == 0) {
if (i % 3 == 0) {
Console.Write("Fizz");
}
if (i % 5 == 0) {
Console.Write("Buzz");
}
}
else {
Console.Write(i.ToString());
}
Console.Write("\n");
}
Just for the sake of perversity, here's a solution written as a Windows .BAT file:
@echo off
for /L %%I in (1,1,100) do call :FizzBuzz %%I
goto :EOF
:FizzBuzz
set I=%1
set /a T3=I %% 3
set /a T5=I %% 5
set /a T35=T3 + T5
if not %T35%==0 goto FizzBuzz5
echo FizzBuzz
goto :EOF
:FizzBuzz5
if not %T5%==0 goto FizzBuzz3
echo Buzz
goto :EOF
:FizzBuzz3
if not %T3%==0 goto FizzBuzzEcho
echo Fizz
goto :EOF
:FizzBuzzEcho
echo %I%
goto :EOF
In action Script ^^
for (var a:Number = 0; a<100; a++) {
if (a%15 == 0) {
trace("Fizz-Buzz");
} else if (a%5 == 0) {
trace("Buzz");
} else if (a%3 == 0) {
trace("Fizz");
} else {
trace(a);
}
}
or
for (var a:Number = 0; a<100; a++) {
trace(a%15 == 0 ? "Fizz-Buzz" : a%5 == 0 ? "Buzz" : a%3 == 0 ? "Fizz" : a);
}
nice lol ...
Bruno Leles on February 28, 2007 4:37 AMI couldn't write down the matrix required for rotating a point in 3D space let alone solve the sine, cosine or other formulas that are plugged into that matrix. But I have written my own 3D game engine. I
can't show you on paper how to compute the distance between two latitude and longitude points, but I write map software for a package delivery company.
But how can that be? This is not trivial programming but according to the author of the article, I don't know how to program because I can't add in hex or solve a bitwise boolean operation in my head. I
argue that a good Software Engineer doesn't need to know how to solve these problems on a piece of paper. THAT IS WHAT COMPUTERS ARE FOR!
As a Software Engineer, problem solving skills are 80% of software engineering. The syntax of programming and programming well is the difference between a good programmer and a great programmer.
I don't need to know the mathematics for rotating a point in 3D space. But as a Software Engineer, I do need to know how to find that formula, how to implement it in code and where to use it.
I was passed over for a job because I couldn't "Write a function to compute the moving average of a stock price." Heck, I didn't even know what a "moving average" was. But when I got home I sat down and 20 minutes later I had a nifty little recursive function that answered the question. Why couldn't I do that in the interview? Because in the interview I didn't have the resources I would normally have while on the job. A good Software Engineer knows how to use those resources to solve programming problems.
I can't add in hex. And I really don't care...
Does that make me a bad programmer?
Bob on February 28, 2007 4:51 AMIt's so BASIC:
for i = 1 to 100
a$ = ""
IF i mod 3 = 0 THEN a$ = a$+"Fizz"
IF i mod 5 = 0 THEN a$ = a$+"Buzz"
IF a$="" THEN print i ELSE print a$
next i
30 seconds (but no PhD)
Tony the Ancient on February 28, 2007 4:52 AMHere's my favorite implementation. It is better then everyone else's because it does not require a single modulo calculation! It can also fit on one line (a really long line!).
printf("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n10\n11\n .... Fizz\n100");
I think the problem is that you are hiring college graduates. Hire the natural self-taught talent! Having a CompSci college degree only means that they wasted 4 years (or more) of their lives. Whereas the self-taught programmers were busy writing software during those 4 years. And, why not test the interviewees on something more pragmatic, like create a business object that handles the CRUDs for s simple 3 or 4 property entity (or test them on something else that would be common for your company to write).
Nathan on February 28, 2007 5:05 AMThought I'd post a version in bash, just for kicks:
#!/bin/bash
TEST_DIVISOR_1=3
TEST_DIVISOR_2=5
UPPER_LIMIT=100
i=1
while [ $i -lt $(($UPPER_LIMIT+1)) ];
do
printed_text=0
if [ $(($i%$TEST_DIVISOR_1)) -eq 0 ]; then
echo -n "Fizz"
printed_text=1
fi
if [ $(($i%$TEST_DIVISOR_2)) -eq 0 ]; then
echo -n "Buzz"
printed_text=1
fi
if [ $printed_text -eq 0 ]; then
echo -n $i
fi
echo ""
i=$(($i+1))
done
no one has done this one either ( I like the '?' operator). Its wonderfully confusing and only two statements:
for(int i=1;i<=100;i++)
printf( !(i%3) || !(i%5) ? "%s\n": "%d\n",
!(i%3) && !(i%5) ? "FizzBuzz":
!(i%3) ? "Fizz":
!(i%5) ? "Buzz":
i);
If you're system does not have modulo (oldschool!) or you're afraid that doing modulo may be a big performance problem (1khz clockspeed) here's a solution that requires only additions:
int m3 = 1;
int m5 = 1;
for(int i=1;i<=100;i++) {
printf( !m3 || !m5 ? "%s\n": "%d\n",
!m3 && !m5 ? "FizzBuzz":
!m3 ? "Fizz":
!m5 ? "Buzz":
i);
if(++m3 == 3)
m3 = 0;
if(++m5 == 5)
m5 = 0;
}
Or if you wanted to make the second half of the loop more complicated and wanted to get rid of all branching (only smart compilers would get rid of the branching), then you could do this:
m3 += (m3 == 2) ? -2 : 1;
m5 += (m3 == 4) ? -4 : 1;
Java Recursive Implementation
public class Fizz
{
public static String fizzbuzz(int i)
{
if (i == 0) return "";
if ((i%3 == 0) && (i%5 == 0)) return fizzbuzz(i-1)+"FizzBuzz\n";
if (i%3 == 0) return fizzbuzz(i-1)+"Fizz\n";
if (i%5 == 0) return fizzbuzz(i-1)+"Buzz\n";
return fizzbuzz(i-1)+i+"\n";
}
public static void main(String[] args)
{
System.out.println(fizzbuzz(100));
}
}
I find there are a lot of people with the ability to memorize code and functions, but without the logical side to put it together. So if you ask what a certain does in PHP for instance, they'll be able to give you the definition. So in their mind the "know programming" but they don't know how to put the pieces together.
Tim Linden on February 28, 2007 5:19 AMJeff Atwood wrote:
>My friend, the internet is your huckleberry. The FizzBuzz programming competition in any language of your choice.
Unbelievable though ... no job board! And all that talent concentrated in one place too.
Brandon Corfman on February 28, 2007 5:20 AM"90% of people can't touch one's elbow with one's tongue."
Hmm, can i?
for(int i=1;i<=100;i++)
{
printf(i%3==0&&i%5==0?"fizzbuzz\n":(i%3==0?"fizz\n":(i%5==0?"buzz\n":"%d\n")),i);
}
Have a nice day!
Drmichi on February 28, 2007 5:21 AMLove my old VB. Do it all backwards.
List1.Clear
Dim n As Integer, out As String
For n = 1 To 100
out = vbNullString
out = IIf(n Mod 3 = 0, "Fizz", vbNullString) + IIf(n Mod 5 = 0, "Buzz", vbNullString)
If out = vbNullString Then out = n
Call List1.AddItem(out)
Next
For all of you self righteous geeks that started your FizzBuzz solutions at 0, your fired (or should I say, not hired) because you don't know how to follow instructions.
As for most of the others, the same! Your grammer and writing skills suck!
There is a lot more to programming than some clever implementation in a dozen different languages. How many of you really spent 30 minutes on your solution but claimed 4!
Michael, that is creative thinking. You're hired! (but if you ever do that in production code, I'll cut your balls off!)
Bob on February 28, 2007 5:37 AMBlazing fast LUT implementation by a coworker:
#include <stdio.h>
#define max 1000000
int main(void)
{
char X[250] = "%d \n%d \nfizz \n%d \nbuzz \nfizz \n%d \n%d \nfizz \nbuzz \n%d \nfizz \n%d \n%d \nfizzbuzz\n\0";
int modu = max % 15;
int full = max - modu;
unsigned int a;
for(a = 1; a < full; a += 15)
printf(X, a, a + 1, a + 3, a + 6, a + 7, a + 10, a + 12, a + 13);
X[modu * 9] = 0;
printf(X, a, a + 1, a + 3, a + 6, a + 7, a + 10, a + 12, a + 13);
}
on second thoughts
For n = 1 To 100
out = IIf(n Mod 3 = 0, "Fizz", vbNullString)
out = IIf(n Mod 5 = 0, out + "Buzz", out)
out = IIf(out = vbNullString, n, out)
Call List1.AddItem(out)
Next
is more consistent
Edward on February 28, 2007 5:43 AMOh, by the way, the max of one million was just for benchmarking purposes. Yes, we were comparing implementations...
John on February 28, 2007 5:52 AMsince you guys coded the solution to the FizzBuzz problem in most of the language and most of the language i know is C based so maybe i thought make an algorithm/pseudo code maybe that's where most new graduates failed to do or atleast imagine in their heads on how to come up with a solution.
1. start
2. declare variable named i
3. declare variables named x and y
4. set x to the remainder of i devided by 3
5. set y to the remainder of i devided by 5
6. if x and y equals to zero print the word FizzBuzz and jump to step 10 else jump to step 7
7. if x equals to zero print the word Fizz and jump to step 10 else jump to step 8
8. if y equals to zero print the word Buzz and jump to step 10 else jump to step 9
9. print the value of i
10. if i is less than or equal to 100 jump increment i by 1 and and jump to step 4 else jump to step 11
11. print the word "Done"
12. end
or at least master the flowchart in their head.
.::zanpakatou::. on February 28, 2007 5:54 AMA recent job I applied for across the country (at the bequest of a friend who later was let go) involved a website with a programming test of ten or so questions of small to moderate difficulty. Most of them said 'in your choice of programming languages'.
Well, since the friend was the test author, and one of the graders, I decided I'd do what it said, and use an obscure language that, pretty much, he was probably the only one to ever have seen; the embedded language in most TinyMUSH-derived games.
I was rejected out of hand because I didn't use one of the languages they had expected...or (probably more likely) understood. That was good enough for ME to know that I didn't want to be there. :)
Anyhow...just to add to the list: FizzBuzz in that language, a couple minutes of work, working the first time, with the (stated) assumption that each number's output will be on a separate line.
@create FizzBuzz
&C-FIZZBUZZ FizzBuzz=$fizzbuzz:@dolist lnum(1,100)=@switch/first 0=mod(##,15),@emit FizzBuzz,mod(##,3),@emit Fizz,mod(##,5),@emit Buzz,@emit ##
Programmers cannot program .... because interviewers can't interview.
I think it's a matter of how easy it seems for a pretender to pass vs the chance to get caught. And obviously people think that it easy to pass an interview even it is not the right job for them (assuming they have a clue that they cannot fulfill the position). I just guess the passed in the past!
And what about the quality of testimonials from previous jobs?
Saw many implementation but no BASH script version, figured I'd include that:
#!/bin/bash
declare CNT=0
while [ $CNT -le 100 ]; do
[ $((CNT % 3)) -eq 0 ] && echo -n "Fizz"
[ $((CNT % 5)) -eq 0 ] && echo -n "Buzz"
[ $((CNT % 3)) -ne 0 -a $((CNT % 5)) -ne 0 ] && echo -n $CNT
echo ""
CNT=$((CNT+1))
done
I'm just leaning java.
more familiar with vb.vet
took 3 minutes - with all of that spent on
sorting out (still unfamiliar) if else {} syntax.
for (int i = 0; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0)
System.out.println("fizzBuzz_3_5");
else if (i % 3 == 0)
System.out.println("fizz_3");
else if ( i % 5 == 0 )
System.out.println("buzz_5");
else
System.out.println(i);
}
Some of the problem has to do with college. A great many schools are selective because there is only a very limited type of student that the teachers will be able to educate. Most schools are ordeals of initiation, especially for undergrads, rather then places of learning. This is especially true for professions like medicine and law, where the real acquisition of knowledge starts at the post-graduate level.
I've had the Reverse Dumb-Ass Test Death Kick done to me. I took a course in number theory, went in to take the test, and had softball questions lobbed at me; better yet, I knew the answers to the questions!
Unfortunately, I wrote the numeral '1' with a serif on the bottom, and the professor insisted I wrote a '2'. Telling him I wrote a '1' did not change his mind.
Shortly after this experience, I decided that most universities are a waste of time, and decided to go learn things on my own.
Anonymous Cowherd on February 28, 2007 6:17 AM@Bob: "I can't add in hex. And I really don't care...Does that make me a bad programmer?"
It makes you prime fodder for either management or sales. Pick your poison.
@Ken "but I have no freaking idea what Hexadecimal maths": OK, maybe it is just my terminology. Do you know what a hexadecimal is? Do you know what 0x0F + 0x01 is? If not, I give up...there is no hope. Maybe you and Bob could start a consulting company together?
With respect to FizzBuzz, if an interviewer ask the question of the phone, and the interviewee can understand it, recognize that some sort of loop is involved, recognize that some sort of logic is inside the loop to determine when to print 'Fizz' and 'Buzz', and is able to communicate this back over the phone in under ten minutes...well, the interviewee just passed the "has a pulse" test for a programming position.
Arguing about what language, syntax, IDE, programming best practices, etc. is way out of scope. The test is to see if some has, at a bare minimum, the raw magic required for programming. I know it is hard to believe, but many people just cannot comprehend things like 'variable reassignment'. Seriously!
Ego has nothing to do with it. We are talking about basic, low level questions that weed out the utterly clueless from the *potentially* clued in. That's it. And doing so saves countless hours of the interviewers time.
To Toepopper,
Your interview question to swap the value of two variables with out using a temp variable is technically impossible. Just because you don't declare a temp variable, the operation a=a+b, uses a temp variable created on the fly. The operation b=a-b, uses a temp variable created on the fly. And the operation a=a-b, uses a temp variable created on the fly. In fact technically three temporary variables are created to perform these three operations...you just didn't declare them.
kcm on February 28, 2007 6:40 AMHmmm,
All this makes me wonder: "Why can't I find a decent programming job?" I can add in hex, and I thought up ways to write the fizzBuzz application in a plethora of different languages/methods.
And it makes me sad to think that this is the state that programming is in, and we wonder why we have software that doesn't work.
[sigh]
But do they have COMMUNICATION/TEAMWORK skills? :/
Another MS SQL version - not elegant, but it works:
note: Begins and Ends not required but included for readability
declare @loopcount int
set @loopcount = 100
while (@loopcount > 2)
begin
if @loopcount % 3 = 0
Begin
print 'Fizz' + cast(@loopcount as char)
End
else
if @loopcount % 5 = 0
Begin
print 'Bang' + cast(@loopcount as char)
End
if (@loopcount % 3 = 0 and @loopcount % 5 = 0)
Begin
print 'FizzBang' + cast(@loopcount as char)
End
set @loopcount = @loopcount -1
end
I cann't resist... some people forget to print the number and another prints the number and the word... The requirements say: "Instead of the number print the word"
for (int i=0; i<101; i++)
{
if (i%3==0)//Print if is multiple of 3 print Buzz and not the #
{
cout << "Fizz";
}
else//not multiple of 3
{
if (i%5==0)//Print if is multiple of 5 print Buzz and not the #
{
cout << "Buzz";
}
else//not multiple of 5
{
if (i%5==0 && i%3==0)//Print if is multiple of 3 AND 5 print
//Fizzbuzz and not the #
{
cout << "Fizzbuzz";
}
else//not multiple of 3 or 5... then print the number
{
cout << i;
}
}
}
cout<<"\n"; //just endline for every case
}
Thanks... it works for C++, Java or C# just change the COUT lines for the output.
DarkChuky on February 28, 2007 6:57 AMI think interview testing can be useful for both the employer and candidate. As a candidate for a job, I always give the following test to the employer. It is very simple:
What do the following acronyms stand for and if you get that far then give me a one-liner describing each:
SRP, OCP, DIP, LSP, ISP
If one or more of the technical people at the potential employer knows what these acronyms stand for and, even better, they know what they mean then I will consider working for them.
Never let the interviewer ask all of the hard questions.
You all have it wrong, the answer is simply:
System.out.println("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\".");
duh...
Me on February 28, 2007 7:13 AMI welcomed Jeff's mention of FizzBuzz. As a novice (and I mean brand-spanking new) programmer being given a "challenge" like that is fun. Currently, I'm in college taking some programming courses. We're learning C# and ASP.NET. So I wrote my own little solution to FizzBuzz in C# via ASP.NET. Even though Jeff's remarks about developers "feverishly posting solutions" is funny, I rather liked seeing how others did it. I realize that with every problem there is more than one way to do it. What really got me confused was trying to figure out what language each poster was using.
Does anyone have a link to more programming exercises I could do? The exercises from the book aren't "real" enough. They ask me to create snippets of code that do something that really isn't useful, but it does test to see if I learned the topic from that chapter. I'd rather make something semi-useful rather than "Create a page in ASP.NET that displays a pop-up message when you click the button."
Thank you in advance.
DarkChucky - that won't work. The situation where it's a multiple of 3 AND 5 will fall into the first part of the if and never make it to the i%5==0 && i%3==0 line. That check needs to be first.
Me2 on February 28, 2007 7:18 AMHey Stu,
It took me 13 years to get a 2 year degree in Data Processing (they didn't call it "Computer Science" back then). Can you infer my intelligence from that? Can you infer my programming skills from my failure to be able to add in hex?
Basically I am a self taught Software Engineer.
Today, I am an independent (currently writing map and delivery software). I charge $127.00 an hour. I have clients banging my door down. They are referred to me by previous clients because of the work I did for them.
So, to the employer who hired the geek, you probably made a good choice. But how many "great" choices did you pass up because they didn't pass your 'brain pan' test?
I still can't add in hex. And I still don't care...
Respectfully, laughing at your ignorance, all the way to the bank...
My PHP version:
for ( $i = 1; $i <= 100; $i++){
if ( $i % 3 == 0 ) $print = 'Fizz';
if ( $i % 5 == 0 ) $print .= 'Buzz';
if ( !isset($print) ) $print = $i;
echo $print.'<br />';
unset($print);
}
Is clear and easy
Now, what worries me is that I'm a designer and I could answer to the questions such as FizzBuzz and some dealing with recursion...
Janne on February 28, 2007 7:31 AMpft..its really easy although time consuming. Thats why I can't see this as a way to test programmers skills... it took me like 30 minutes to solve this problem. each candidate * 30 minutes...figure it out!
anyway, here is my solution. (I had to use calculator after 25)
print 1
print 2
print "Fizz"
print 4
print "Buzz"
print "Fizz"
print 7
print 8
print "Fizz"
print "Buzz"
print 11
print "Fizz"
print 13
print 14
print "FizzBuzz"
print 16
print 17
print "Fizz"
print 19
print "Buzz"
print "Fizz"
print 22
print 23
print "Fizz"
print "Buzz"
print 26
print "Fizz"
print 28
print 29
print "FizzBuzz"
print 31
print 32
print "Fizz"
print 34
print "Buzz"
print "Fizz"
print 37
print 38
print "Fizz"
print "Buzz"
print 41
print "Fizz"
print 43
print 44
print "FizzBuzz"
print 46
print 47
print "Fizz"
print 49
print "Buzz"
print "Fizz"
print 52
print 53
print "Fizz"
print "Buzz"
print 56
print "Fizz"
print 58
print 59
print "FizzBuzz"
print 61
print 62
print "Fizz"
print 64
print "Buzz"
print "Fizz"
print 67
print 68
print "Fizz"
print "Buzz"
print 71
print "Fizz"
print 73
print 74
print "FizzBuzz"
print 76
print 77
print "Fizz"
print 79
print "Buzz"
print "Fizz"
print 82
print 83
print "Fizz"
print "Buzz"
print 86
print "Fizz"
print 88
print 89
print "FizzBuzz"
print 91
print 92
print "Fizz"
print 94
print "Buzz"
print "Fizz"
print 97
print 98
print "Fizz"
print "Buzz"
I've only been programming a little under a year, but I don't think that I could do the FizzBuzz program off the top of my head. Why? Well, the idea of the loop is simple enough, however I have NEVER needed to know if a number was divisible by another, so I have no idea what function finds that for me. If I were given the chance to look that part up, then I wouldn't have any trouble.
jread on February 28, 2007 7:43 AMAmazing. The comments on this thread are full of people criticizing the article, but it seems like *most* of the code examples posted here appear to completely back it up! It is shocking how many of the "coders" that posted here did not do simple things like initialize their variables - resulting in code that counts from 0-100 (read that as false positives since 0 mod 3 and 0 mod 5 = 0) - or display ALL numbers INCLUDING multiples of 3 and 5.
Maybe the problem is not so much that most "programmers" can't code, but that they can't follow directions.
Ignoring the language for now, the simplest way to do this is IMO:
for (int i = 0; i < 101; ++i)
{
if (i % 3 == 0) then
{
printf("Fizz");
}
else
{
if (i % 5 == 0) then
{
printf("Buzz");
}
else
{
printf("%d", i);
}
}
}
Here's a more elegant MSSQL version that improves on the one above by using fewer variables, fewer checks and SELECT instead of SET (SELECT is apparently a little faster).
DECLARE @i int
DECLARE @text varchar (8)
SELECT @i = 1
WHILE @i < 101
BEGIN
SELECT @text = ''
IF (@i % 3)
SELECT @text = 'Fizz'
IF (@i % 5)
SELECT @text = @text + 'Buzz'
IF (@text = '')
SELECT @text = @i
PRINT @text
SELECT @i = @i + 1
END
WHERE IS THE COBOL?!?!?
Man, it's been years...
*************************************
*
*
* This is what a cobol program used to look like....
*
*
**************************************
*First you had your variable declaraction section or something...
WS-COUNT-LOOP = TYPE INTEGER;
bla bla bla!! Man, I can't remember it at all... had to learn that stuff freshman year...
Schmeckendeugler on February 28, 2007 7:53 AM^ Need I say more? ^
blakhatt on February 28, 2007 7:54 AMits probably due to the fact that most web app programmers dont have to do lame-ish tasks like that
tj on February 28, 2007 7:58 AMThis is so demonstrative. How many programmers does it take to read the requirements? I thought they were painfully obvious. It's not like in real life where the user just says:
"I want something that will let me take my data out of AutoCad2000 and enter it into our custom database written in 1988 by a lame-ass who can't program. By the way, I won't be available for comment, and I need it done in two weeks."
While I'm aware you could probably do something to short these if's using bit math, this is my unoptimized solution:
// Run with cscript/E:JScript [filename]
for(i = 1; i < 101; i++)
{
if(i & 15)
WScript.Echo("FizzBuzz\n");
else if(i & 3)
WScript.Echo("Fizz\n");
else if(i % 5)
WScript.Echo("Buzz\n");
else
WScript.Echo(i+"\n");
}
// compile with dmd -release -O [filename]
for(int i = 1; i < 101; i++)
{
if(i & 15)
printf("FizzBuzz");
else if(i & 3)
printf("Fizz");
else if(i % 5)
printf("Buzz");
else
printf("%d",i);
printf("\n");
}
// Note that any case where you have a 2^x - 1, you can use '&'
// instead of %, and it'll run faster. An optimal solution would
// trim out the branching, probably with some bitmath.
// After 0x0F comes 0x10.
// Right now on my spare time I'm the project maintainer for Walnut:
// http://dsource.org/projects/walnut
// A JScript engine. It's a mature project, and I'm implementing
// a COM client for it.
// I'm currently employed as an office assistant, because I can't get
// a job as a programmer. You can reach me at murpsoft@hotmail.com
// I am willing to move, but prefer to telecommute.
Public Function BizzFuzz(ByVal int As Integer)
Dim i As Integer
For i = 1 To int
If (i Mod 3 = 0) And (i Mod 5 = 0) Then
Console.WriteLine("FizzBuzz")
ElseIf i Mod 3 = 0 Then
Console.WriteLine("Fizz")
ElseIf i Mod 5 = 0 Then
Console.WriteLine("Buzz")
Else
Console.WriteLine(i)
End If
Next
End Function
A little late; but I figured I'd throw in a CL version:
(loop for i from 1 to 100
do
(or
(some #'identity
(list
(if (zerop (mod i 3)) (progn (format t "Fizz") t))
(if (zerop (mod i 5)) (progn (format t "Buzz") t))))
(format t "~A" i))
(terpri))
Python one-liner:
print map(lambda x: 'FizzBuzz' if x%15 == 0 else 'Fizz' if x%3 == 0 else 'Buzz' if x%5 == 0 else x, range(100))
This could probably be replaced with a list comprehension.
Nathan Forget on February 28, 2007 8:14 AM@Bob: You are making that kind of money, have a technical degree, call yourself a 'software engineer', have been doing this for years...and *still* cannot add 0x0F + 0x01? Sounds to me like you went into sales a looooong time ago.
Whatever, good for you.
But you should not mistake FizzBuzz, the great hexadecimal maths question of 2007, or any other similar *basic* aptitude/knowledge test as an intelligence metric. There are plenty of brilliant people out there who cannot program, and there are lots of full blow morons who can. (I have a link to a great paper on the subject of “programming aptitude” from a university, but can’t find it at the moment. If someone knows what I am talking about, please post! Basically, some people have “it” and some don’t…and the correlation with intelligence is weak. The paper was from a CS academic and was an analysis of his/her students’ performance on an aptitude test that focused on variable assignment concepts.)
People interviewing for a position frequently find themselves with 25, 50, or even more CVs to consider. As anyone who’s hired more than a few people can attest to, the ‘perfect’ CV does not make a perfect candidate. We have to look at folks with a wide range of experiences and we have to weed out the time wasters who’ve some how managed to deceive their way into software development. Bringing everyone in for a one, two or three hour interview? Have one, two or three people from the team in on the interview? It adds up. So we do phone interviews with trivial questions. It works. I am completely comfortable with my tactic of asking a few basic CS questions to see if they are a pretender or not.
“…how many "great" choices did you pass up [that cannot do FizzBuzz, add 0x0F + 0x01, etc?¨] Not many, that is for sure.
BTW: Do you have any constructive ideas on how to separate the programming wheat from the non-programming chaff?
Python one-liner:
print map(lambda x: 'FizzBuzz' if x%15 == 0 else 'Fizz' if x%3 == 0 else 'Buzz' if x%5 == 0 else x, range(1, 101))
This could probably be replaced with a list comprehension.
Nathan Forget on February 28, 2007 8:31 AM(awk)
BEGIN {
i = 0;
while (i<100)
{
i=i+1;
if (int(i/3)*3==i && int(i/5)*5==i)
{
print "FizzBuzz";
continue;
}
if (int(i/3)*3==i)
{
print "Fizz";
continue;
}
if (int(i/5)*5==i)
{
print "Buzz";
continue;
}
print i;
}
}
Merle Zimmermann on February 28, 2007 8:43 AMbzzzt... another wrong answer Bassam! 1. You started at 0. 2. Your logic is wrong (what would 15 do?).
Okay, since I ended up posting, I'll post the code I jotted down when I read this post. (It took me about 4 min) (Perl)
for my $num (1..100) {
print $num if ($num % 3 and $num % 5);
print "Fizz" unless $num % 3;
print "Buzz" unless $num % 5;
print "\n";
}
I think it's fairly readable (especially compared to the other Perl solutions :P). In a real-world scenario, though, if code maintainers were not likely to know Perl well, I'd probably avoid the trailing-ifs and "unless" because I've seen these things confuse people.
I like the comments about asking questions of the interviewers regarding what to optimize for (readability? execution speed? brevity?) and whether this was likely to change, etc. Also, parameterizing the input instead of hard coding would possibly be a good way to do it (unless you had to do it in as short a time as possible). These little extra things (combined with, of course, a working program) would make you stand out in an interview.
Mark on February 28, 2007 8:43 AMJavascript fizzBuzz
for(var i=1;i<=100; i++) {
if((i%3==0) && (i%5==0)) document.write("FizzBuzz<BR>");
else if(i%3==0) document.write("Fizz<BR>");
else if(i%5==0) document.write("Buzz<br>");
else document.write(i +"<br>");
}
Jeff, having 'programmers' attempt to write this type of program in an interview surely will weed out a crap load of candidates...but just because you can write the FizzBuzz program within a couple of minutes on a piece of paper doesn't really mean much either.
From what I can see it only means you understand IF statements and comparison operators. I know designers who are crafy at coding JavaScript who can pull this program off in 5 minutes but I wouldn't dare consider them for a real programming job. Why? Well this is just really the tip of the ice-berg...and I liken being able to code this statement as someone capable of changing their car's oil. Which by the way a crap load of people can't do either. Of course would you call the few souls who do change their oil mechanics???
-Ralph
Ralph on February 28, 2007 8:53 AMJeff,
The ADO.NET Orcas Entity Data Model will significantly reduce the code required for both Fizzing and Buzzing activities. Additionally, you may gain value from the ASP.NET AJAX Framework, which can update your end user's page with Fizzes and Buzzes as they are computed.
Hope this helps,
Scott
I think little coding exercises like this are far more interesting that flash games and NSFW articles/pics to pass time...LETS HAVE MORE OF THEM!
~ Matt
<?php
$x=1;
while ($x<101) {
if ((($x%5) == 0) and (($x%3) == 0)){
print "five AND three </br>";}
else if (($x%3) == 0) {
print "three<br/>";}
else if (($x%5) == 0) {
print "five<br />";}
else {
print "$x<br />";
}
$x += 1;
}
print "You truly are, the king of kings!";
?>
Because we all know how high the command is for TI-83 basic. :P
a=0
label a
a+1=a:a/3=b:int(b)=c:a/5=d:int(d)=e
if a>100:then
stop:end
if b=c:then
if d=e:then
print "fizzbuzz":goto a:end
print "fizz":goto a:end
if d=e:then
print "buzz":goto a:end
Far too many comments for me to read through, so forgive me if this has already been stated.
Regarding the no-temp-variable swapping: For one I don't think this says anything toward or against anyone's programming ability. Especially since the solution offered won't work in every case.
The biggest flaw with the plus/minus solution is that overflow can and will occur for large numbers. The better solution is to use three XOR operations. And even that obviously wont work for non-numeric variables (strings, objects, etc).
And it appalls me to see so many people actively not using loops and calculation in the FizzBuzz problem. (i.e. the people listing "print 1, print 2, print "fizz" .... etc.) If I were hiring a developer and had a candidate that said outright "I don't know" versus a person who did this, I'd take the "I don't know" guy/gal.
LightningStorm on February 28, 2007 9:07 AMI agree with the one who says, if u want a good programmer, don't put the contraint (must hire only graduates), being one does not guarantee success at all. I code since 1990 and have seen lots of good software developers and most of them where just self-taught. Important organizations have lost worthy resources because they were asked to hire graduated people just to fulfill requirements for the job's description. FizzBuzz test can be a good thing but it cannot be the only thing to test a good programmer, because some clever minds owners that don't have resources to get a degree may be awaiting for someone to help them launch the rocket, then they will take you to mars and venus, who knows, but If you don't give the chance, someone else will do.
jotape on February 28, 2007 9:07 AMFar too many comments for me to read through, so forgive me if this has already been stated.
Regarding the no-temp-variable swapping: For one I don't think this says anything toward or against anyone's programming ability. Especially since the solution offered won't work in every case.
The biggest flaw with the plus/minus solution is that overflow can and will occur for large numbers. The better solution is to use three XOR operations. And even that obviously wont work for non-numeric variables (strings, objects, etc).
And it appalls me to see so many people actively not using loops and calculation in the FizzBuzz problem. (i.e. the people listing "print 1, print 2, print "fizz" .... etc.) If I were hiring a developer and had a candidate that said outright "I don't know" versus a person who did this, I'd take the "I don't know" guy/gal.
LightningStorm on February 28, 2007 9:08 AMi haven't used MOD since my vb.net class. and it's never come up in the real world so far, so, i might just have tanked on the question.
i know in an interview once i was asked how i would reverse a string in vb.net - and my brain went thru getting the length - then setting up a loop etc and on and on. and later i learned there was already a function in the language "StrReverse". so, i can see how it's pretty hard to set an interview test to target a potential employee's experience. the best interview i had, they gave me a pc, Visual Studio 2003 + sql server 2000 and said you've got 45 minutes, here's the sa login. make a web application that pulls this and that. no inline sql (only stored procedures and they wanted it in tiers [data-access, business logic etc all in separate assemblies). i aced that in 25 minutes. but, i had been programming like that (at the time) for two years. i'm afraid that would be easier for me than FizzBuzz.
My impression is that interviewers that give programming tests at best are merely demonstrating that the don't understand human nature and at worst don't actually know how to program themselves.
For those that think that tests are relevant have you actually bothered to test the test itself? Have you done the following procedure?
1. Created a written form of the test.
2. Distributed to developers at your company or perhaps even a sample test group
3. Provided a negative incentive such as telling them that their results will be reflected on their next performance review. (This is to provide the ever popular 'under pressure' climate which tests are usually rationalized with.)
4. Required that they do it with no references and no interaction with their co-workers.
5. Using the results from above process to create what a 'correct' solution looks like and to have some idea of what variances might occur.
If you have done the above then your test actually has some meaning. If not then you are merely deluding yourself into believing that your test has any objective meaning at all.
I have seen the following at interviews.
A. The interviewer provided a test which they obviously made up during the interview itself. It took longer for them to describe the requirements of the test (and to figure them out via my questions) then it did for me to answer it.
B. The interviewer tested me with a simple code example. I answered and then commented on the fact that I had answered exactly the same question in the last week on a popular language programming news group. The interviewer became very flustered and was actually somewhat incoherent for the rest of the interview.
C. One interviewer tested me with an excercise that required GUI knowledge. I repeated verbally what was witten on my resume that I hadn't worked on GUIs in years and that I wasn't applying for a position that had anything to do with GUIs. Actually I emphasized that and the interviewer assured me the position didn't need GUIs. And yet the interviewer still insisted that I needed to attempt the test.
Myself I have found the following (yes I have been responsible for technical interviews in the past.)
1. I attempt to determine if the person is open to criticism of their work. (I give tests so that I can criticise their work and see how they react.)
2. Does their history and the interview process lead to the conclusion that they are willing to learn?
3. Do they exhibit the ability to both listen and verbally communicate?
Given that a candidate passed the above in a positive way then that is all that matters. I do this because I don't believe it is possible to give a 5 minute (or hour) test and accurately determine even within a broad scope the programming ability of anyone. I also know that people are seldom productive the first day on the job. However people that can learn and learn from criticism will be more productive in a year than they are now regardless of their ability. And that does matter.
Finally I must mention that all of this completely ignores the fact that interviewers themselves are often incompentent in the interview process. For example..
1. One interview process (which I was not part of) consisted of two interviewers arguing with each other for 15 minutes while the interviewee was sitting there.
2. One interviewer couldn't even express questions coherently.
3. At more that one interview it was very obvious that the interviewers hadn't even read my resume, hadn't bothered to even prepare for the interview process and had a significant problem keeping a dialog going.
4. At one interview within five minutes it became obvious that not only the interviewers (none of them) had bothered to read my resume but apparantly no one else at the company had either. I had absolutely no experience in the job that they were looking to fill and they were definitely looking for experience.
With C:
for (int i=1; i<100; i++)
{
if (!i%3) printf("Fizz");
if (!i%5) printf("Buzz");
if (i%3 && i%5) printf("%d",$i);
printf("\n");
}
Ok, everybody, prepare for the horror as I, who has never learned any programming language since the C64, writes fizzbuzz.
10 i = 0
20 i = i + 1
30 if i / 15 = int(i / 15)
40 print "FizzBuzz"
50 elseif i / 5 = int(i / 5)
60 print "Buzz"
70 elseif i / 3 = int(i / 3)
80 print "Fizz"
90 else
100 print i
110 endif
120 if i < 101
130 goto 20
140 else
150 quit
I probably got the syntax completely wrong....
I think asking a programmer to write at least some code in an interview can only be a good thing. Those that enjoy or are any good at it will thrive on attempting to answer the question. Those that don't enjoy it will just normally sit there staring, thinking, but not attempting. It doesn't necessarily have to be a code or logic based problem, just any problem which requires a bit of thought and effort.
Whether it is completely correct first time, is neither here nor there - how many developers write 100% bug free code, every time? Why do we use debuggers? Test Driven Development? Granted, these should really be last resort techniques used after a very good initial attempt. Be great if somebody had a go in an interview using TDD, on paper!
My personal though is that this sort of question should be used solely to see how a candidate approaches the problem. If they sit there and cry, then you know they are unlikely to handle any sort of pressure situation. If they get it wrong, so what!, let them know it's not quite right and ask them if they can spot the error against the requirements (debugging). If their code is correct but verbose, ask them if they can refactor it, so that it does the same thing a) more efficiently OR b) with more maintainable code. You should also present them with a mess of code that does the same thing, and ask them to a) work out what it does [understanding others code and methods] and b) spot any errors [debugging other peoples code]. These are the practices that are required by a "developer" (not a programmer), and so long as they understand why they're needed, and make a good attempt, they're potentially a good candidate.
Granted, if we could all write 100% correct code in our head (without a computer), we'd have a world full of wonderful, never failing software.. this ain't a perfect world though!
A personal gripe of mine .. I find spelling mistakes in code to be my biggest bane, especially those where the developer has copied and pasted throughout and never spotted it! Or has just continued spelling it wrong, because they couldn't be bothered to correct it.
kcm: "Your interview question to swap the value of two variables with out using a temp variable is technically impossible."
Wrong. See my post above that shows, step by step, how to do it using XOR. Since the intermediate results are stored in the variables being swapped, no temp variable is required.
I will sell a FizzBuzz cheat sheet to anyone interested. You name the language, I'll name the price. No job to small, no fee too large...
What I have learned in my few years of solving problems, is that the best problem solvers know how to find answers and do not necessarily rely on rote memorization of language syntax.
Test your canidates on ability to find solutions...
If I don't know something I will tell you, and if I cannot fathom the answer, I will tell you that as well. But do not deny me the answer and the reasoning behind the answer, or it will drive me nuts whilst I search for the answer (and I mean to the point of troubled dreams)
But, thats me and my problem solvers complex...
The Blackfox on February 28, 2007 9:54 AMI have a MS degree in CS, over 25 years as a software engineer, several years of teaching graduate students in CS. I have been on both sides of the hiring process. My personal opinion is that you can see morons on either side.
I'll start with the lousy programmers. I never give candidates recursion tests, nor tree traversing, or swapping two variables without using temp. Most of these are tricks, which don't show candidate's ability to program, but show how “smart” the interviewer is. Of course, I do ask them to tell me about it, but it's strictly conversational, and that's enough. And don't forget that embedded programming is not a financial programming, not databasing, not genetics, not statistics, neither web. These are different object models with different objectives.
Still if I have to ask them about coding I suffice with the IF statement. It's so common that one can not overestimate its importance. Its use shows how much you know the boolean basics, the functional basics, the assignment rules, etc.
So here is my test:
if var1 = true then
var2 = true
else
var2 = false
end if
or C#, Java style:
if (var1 == true )
{
var2 = true
}
else
{
var2 = false
}
The question is: How can you rewrite this in one line statement?
Well, the answer is:
var2 = var1
I give them the answer and ask them to explain. Most of them don't understand why var2 = var1. I have encountered this or similar type of coding thousands of times. They never heard of *truth tables*, they didn't know how to verify their complex IF statements. Would I hire such a person? Depends on the chemistry, maybe I'll teach him later...
Now about the lousy interviewers. Yes, most of them are like that. Usually, (MS, Amazon, other big companies) conduct the phone interview using lists of predefined questions and answers, and the interviewers don't understand anything and if you say something different you loose. I had similar experience, where a girl straight from the college interviewed me (I had over 20 years of programming at that time), using a list with questions that she did not understand, but still she insisted on her opinion. Would I go to that company? No.
There are others, who just want to tickle their ego - they know few algorithmic tricks and ask you to invent that in front of them (if you did not know it beforehand). Well, I usually ask them too – to explain the bubble sort algorithm or something else.
Most of the questions on interviews are on algorithms. This is wrong. Much more universal and useful is to ask about program structures, structured and object oriented programming, using unit testing, debuggers, source safe and other productivity tools. I was amazed when a candidate with otherwise strong appearance did not like using a debugger - he liked using "printf".
The process of hiring the right person is complex. There is luck, there is chemistry. After many years I understood that people work in teams and you should not hire the best knowledgeable programmer, but the fittest (to your team) person.
George on February 28, 2007 9:56 AMOver here at FogCreek we're working on a few updates to Wasabi for this very purpose so we can compile our FizzBuzz implementation into PHP and VBScript.
In fact, I think it would make good sense for us to create a new language specifically for FizzBuzz implmentations on the web. We'll call it "Horseradish".
Joel Spolsky on February 28, 2007 9:57 AMWow, I don't think I've seen THIS many responses in Jeff's threads yet! 8^D
It has probably been mentioned amongst the code, but in my mind, there has always been a clear distinction between semantics and syntax in programming. Semantics is the WHY if our trade, Syntax is the HOW.
While this may seem moot, it is important to remember that the semantics will always be around while the syntax is ever evolving. It doesn't matter if its .NET, Java, LISP, or Eiffel, a FOR loop solves one issue while a recursive call will solve another and the nuances of why they do it are important. Once you know this, hashing it out using the proper terminology becomes moot. I have picked up a few new languages along the way quite easily since I took the time in college to master the semantics of programming.
I think the web has gone a long way to put a lot of the semantics into the syntax. Since web oriented programming/apps (the field I work in) is pushing itself around data parsing/presenting/storing, a lot of the tricks that SQL gives us solves the issues for us. I could only imagine what things are like if you're working for JPL or somewhere else where you're designing the software to respond within a certain time frame to an event. The speed and resources used could mean life or death out in space and the use of an If/Else vs. a Switch statement means a heck of a lot more.
Today's environment is being heavily dominated by web based/oriented apps and if you know where to snag some code, or drag in that nifty control in Visual Studio/Eclipse, most of your work is done for you. The third/fourth tier languages make everything practically verbal, so its not too hard to see folks coming into the ranks that know how to put two and two together. Give them a challenge out of the norm, or for which they don't have resources readily available, and then you can see what kind of "programmer" they are.
Speaking of which, did anybody use a Case/Swtch statement yet in their FizzBuzz solution? I would have gone that route 8^D
Sean Patterson on February 28, 2007 10:00 AM
25 should be "fizzfizzfizz" since it can be divided by 5 twice, and being an odd multiple of 5, is has the number 5 in it; which code is easiest modify to include this rule? It can also be played using roman numerals, hence 8 = VIII gets one fizz; which code is easiest to generalize?...
Here is the way I would code it in Javascript:
for ( var i=1; i <= 100; i++ )
document.write("FizzBuzz".slice(i%3&&4, i%5?4:8) || i);
For readable output, add spaces or HTML to taste.
> Over here at FogCreek we're working on a few updates to Wasabi for this very purpose so we can compile our FizzBuzz implementation into PHP and VBScript.
Nice.
Also, I apologize for the errors on comment submission. This is a limitation of Movable Type; it re-renders the entire HTML for the post every time a comment is submitted. So if two people enter comments at the same time, you'll see an error (but your comment *IS* saved).
Yes, I realize this sucks, but it's typically not an issue until you have a post that goes hyper-viral (WTF?) and people are commenting every 5 seconds for hours on end.
Jeff Atwood on February 28, 2007 10:16 AMIt's amusing to see this kind of blog including its comments.
Really.
Half of those who posted the solutions didn't read the questions completely (the fact that you didn't print out the number).
The other half who completed the solutions are either:
a) not optimized (1/3)
b) wrote ugly code (1/3)
c) did well. (1/3)
I'm also amazed to see the reply/reaction/whatsoever that "asking fizzbuzz is not ideal", "why do they ask <insert_problem> for production code", "the interviewer is nuts", etc.
To those who pinch their 2cents saying that "as long as you can learn new things quickly", I'd say: "good for you" and I'd say: "your 3 hours code XML-oompaloompa must be suck to maintain". But it's all good, you shipped. Congratulation. I bet someone will write a blog post about "just because you're a quick learner doesn't mean you can write clean, production level code" after this.
And this came from the audiences of Coding Horror blog.
I heard Google/Microsoft/Amazon interview is quite challenging, why don't all of you guys at one point in your life take that interview before you post any code or comment here acting like the "ideal professional programmers" according to "ideal bloggers". (For those of you who are currently working there, good for you, you're a solid software developer)
The only ideal developer you would've hired is YOURSELF if this is the case with all the interviewing processes. Admit it, you think you're better than anyone ^_^
Is it a matter of a solution that works or the quality of the solution? The following Perl code works (don't laugh; I've met programmers who code solutions this way), but would you hire the author?
$i = 1;
$val = { 3 => 'Fizz',
5 => 'Buzz',
6 => 'Fizz',
9 => 'Fizz',
10 => 'Buzz',
12 => 'Fizz',
15 => 'FizzBuzz',
18 => 'Fizz',
20 => 'Buzz',
21 => 'Fizz',
24 => 'Fizz',
25 => 'Buzz',
27 => 'Fizz',
30 => 'FizzBuzz',
33 => 'Fizz',
35 => 'Buzz',
36 => 'Fizz',
39 => 'Fizz',
40 => 'Buzz',
42 => 'Fizz',
45 => 'FizzBuzz',
48 => 'Fizz',
50 => 'Buzz',
51 => 'Fizz',
54 => 'Fizz',
55 => 'Buzz',
57 => 'Fizz',
60 => 'FizzBuzz',
63 => 'Fizz',
65 => 'Buzz',
66 => 'Fizz',
69 => 'Fizz',
70 => 'Buzz',
72 => 'Fizz',
75 => 'FizzBuzz',
78 => 'Fizz',
80 => 'Buzz',
81 => 'Fizz',
84 => 'Fizz',
85 => 'Buzz',
87 => 'Fizz',
90 => 'FizzBuzz',
93 => 'Fizz',
95 => 'Buzz',
96 => 'Fizz',
99 => 'Fizz',
100 => 'Buzz'};
while ( $i < 101 ) {
$p = $val->{$i} ? $val->{$i} : $i;
print "$p\n"; $i++
}
As far a recursion goes, I think whether you need to use it or not depends on what problems you're solving. I don't think we can assume that solutions aren't optimal just because recursion is never used. I was probably 15 years in the business before I found a need to use recursion in the real world. Of course, when I did run across the need, at least I knew what it was.
Well, the site maintainer removed a snippet from my post showing an error from the site; probably for security reasons, but it'd been nice to leave an [edited] note.
~~~~
I'm quite certain that university is absolutely USELESS when it comes to software engineering/development. Most profs learned from their profs, and so they learned Pascal and VB and Basic. In real life, most people currently use C, C++, Java, JavaScript and XML.
In university, they take two weeks to teach the concept of an array, something which I taught (effectively) to a friend in roughly 30 minutes; including looping, pointers, memory, and slicing (which you don't get in university until what... never?)
My prof didn't understand that Java had been programmed in C, and is usually really translated when you run javac, and JITC'd. My TA was quite adamant that ASCII has always been 8-bit, when in fact it started out from 0-7F, and was later extended with high ASCII and then more or less replaced with UTF-8.
They live in their own little world, away from real life. It really pisses me off that companies only hire graduates.
There should be a Profession for Software Engineering. A computer Science degree is a waste of space. It's over bloated with unnecessary Math classes and needs more classes geared towards what happens in the real world. They're still working on a 1980/early 1990's structure in the degree. Any real IT guys/programmers in the Industry will tell you that if you want to make the real money - go get an Engineering Degree. They get paid more, get the better positions and have more respect.
Not to mention half the instructors for CS degrees are ancient and need to meet modern reality.
The E on February 28, 2007 10:33 AMI am studying for a degree at the moment, and I can see what you are saying Jeff. This problem is not necessarily the individuals fault, imho it is more down to the education system (in england).
I intend to become a professional programmer but from what I can see so far the IT course I am doing will not provide me with any practical programming skills. It will however give me a degree which shows that I can program in C, Javascript, Java, etc.
Just today I had my final C assignment marked. I got 84%. My code was fine but I lost marks for some omissions in my documentation such as not explaining what I had learnt from the assignment.
A friend of mine got 100%. This is nice but surprising considering that he wrote a program which in all practicality required a loop, without the use of one.
I have to admit my documentation has always been a bit on the sloppy side, but I do like to take my time ensuring that I produce code that is fast, effective, and easy to build upon. Unfortunately this does not seem to hold any weight as I could get a degree with the highest mark possible without even knowing how to use a FOR loop. Just some proof for you ;)
Mike on February 28, 2007 10:37 AMprivate void FizzBuzz()
{
for (int i = 1; i <= 100; i++)
{
string Output = i.ToString();
if ((i % 3) == 0)
Output = "Fizz";
if ((i % 5) == 0)
Output = "Buzz";
if ((i % 3) == 0 && (i % 5) == 0)
Output = "FizzBuzz";
//Convert.ToString(i % 3)
Console.WriteLine(Output);
}
}
It seems to me that the ability to program is rare because the ability to think about things as a series of steps is so rare.
I've met smart people who can't break down a trip to the grocery store into a step-by-step sequence.
It seems that those who can do this can code, those who can't cannot, and there's no hope for them, either.
By the way, my Perl solution (which only took a few minutes to write/run/debug--you DO let the candidates have a computer to do this right?):
for (1..100){
if ($_ % 3 == 0) {print "Fizz"}
if ($_ % 5 == 0) {print "Buzz"}
if (($_ % 3) > 0 && ($_ % 5) > 0) {print "$_"}
print "\n";
}
sorry for the previous posts :s
print(substr(fread($f=fopen('http://golf.shinh.org/p.rb?FizzBuzz','r'),2243),1721,522));fclose($f);
flo on February 28, 2007 11:09 AMI had a 2 semester course in graduate school called "Natural Language Processing" which focused on compiler and writing compilers. This course was amazing and I have been using the same routines for a wide variety of applications for years. The most handy tools & techniques were parsing, recursion, multiple linked lists and trees. Enclosed is bit of code that is a real test of reading code with recursion. The code is used to balance an existing binary tree. Enjoy..
#include <stdio.h>
typedef struct treenode
{
struct treenode *left;
struct treenode *right;
} TREENODE;
static int list_num;
static TREENODE list_base;
static TREENODE *list_tail;
static TREENODE *root;
static int left;
void *balance( void *old_root );
static void list_build( TREENODE *node );
static TREENODE *form_tree( int );
void *balance( void *old_root )
{
if( old_root == NULL ) return( NULL );
list_tail = &list_base;
list_num = 0;
list_build( old_root );
root = list_base.right;
left = 0;
return( (void *)form_tree( list_num ) );
}
static TREENODE *form_tree( int num )
{
int middle;
TREENODE *ptr;
middle = ( num >> 1 );
if( num == 5 ) middle++;
if( left ) middle = num - middle - 1;
left = 1;
ptr = ( middle > 0 ) ? form_tree( middle ) : NULL;
root->left = ptr;
ptr = root;
root = root->right;
left = 0;
middle = num - middle - 1;
ptr->right = ( middle > 0 ) ? form_tree( middle ) : NULL;
return( ptr );
}
static void list_build( TREENODE *node )
{
if( node->left ) list_build( node->left );
list_tail->right = node;
list_tail = node;
list_num++;
if( node->right ) list_build( node->right );
}
I have a MS degree in CS, over 25 years as a software engineer, several years of teaching graduate students in CS. I have been on both sides of the hiring process. My personal opinion is that you can see morons on either side.
I'll start with the lousy programmers. I never give candidates recursion tests, nor tree traversing, or swapping two variables without using temp. Most of these are tricks, which don't show candidate's ability to program, but show how “smart” the interviewer is. Of course, I do ask them to tell me about it, but it's strictly conversational, and that's enough. And don't forget that embedded programming is not a financial programming, not databasing, not genetics, not statistics, neither web. These are different object models with different objectives.
Still if I have to ask them about coding I suffice with the IF statement. It's so common that one can not overestimate its importance. Its use shows how much you know the boolean basics, the functional basics, the assignment rules, etc.
So here is my test:
if var1 = true then
var2 = true
else
var2 = false
end if
or C#, Java style:
if (var1 == true )
{
var2 = true
}
else
{
var2 = false
}
The question is: How can you rewrite this in one line statement?
Well, the answer is:
var2 = var1
I give them the answer and ask them to explain. Most of them don't understand why var2 = var1. I have encountered this or similar type of coding thousands of times. They never heard of *truth tables*, they didn't know how to verify their complex IF statements. Would I hire such a person? Depends on the chemistry, maybe I'll teach him later...
Now about the lousy interviewers. Yes, most of them are like that. Usually, (MS, Amazon, other big companies) conduct the phone interview using lists of predefined questions and answers, and the interviewers don't understand anything and if you say something different you loose. I had similar experience, where a girl straight from the college interviewed me (I had over 20 years of programming at that time), using a list with questions that she did not understand, but still she insisted on her opinion. Would I go to that company? No.
There are others, who just want to tickle their ego - they know few algorithmic tricks and ask you to invent that in front of them (if you did not know it beforehand). Well, I usually ask them too – to explain the bubble sort algorithm or something else.
Most of the questions on interviews are on algorithms. This is wrong. Much more universal and useful is to ask about program structures, structured and object oriented programming, using unit testing, debuggers, source safe and other productivity tools. I was amazed when a candidate with otherwise strong appearance did not like using a debugger - he liked using "printf".
The process of hiring the right person is complex. There is luck, there is chemistry. After many years I understood that people work in teams and you should not hire the best knowledgeable programmer, but the fittest (to your team) person.
George on February 28, 2007 11:18 AMTo "Dan" and "The E". Shame on you for blaming education systems.
Actually, sucks to be you guys if you went to podunk college and looking to hire students from that same podunk college.
Why don't you try and lure MIT students? UC Berkeley? or perhaps Stanford people? Waterloo up North? or perhaps students who did very well in ANY CODING COMPETITION (Topcoder comes to mind or Google SoC). You might actually get a solid problem solvers instead of someone who can _JUST_ write C/C++/Java and XML-oompaloompa.
The problem is: you don't know where to look. That also puts you in a bad situation: incapable of looking decent developers. Which leads you to an unfortunate complex problem: your company now is filled with not-so good developers because you don't know where to look, therefore these top coders won't work there.
Let's quit bitching, if you want to have good colleagues or undermen, hire them yourself, look for them from where they belong. And if you get a raw talent, teach them, mentor them.
If you're suck at mentoring them, who would want to work for you. If my boss expects me to know it all, why the heck I need a boss for?
Oh and to "The E", I bet your school is a very small school that only gives bachelor degree (or maybe just diploma).
Have you ever heard this thing called "funding" for research where the profs actually fight for the money so bad? Well, in my university, profs actually do research. They came up with AspectJ, some fancy mammoth filesystems, some fancy Task plugin in Eclipse. Algorithm used by Starwars movies.
Quit bitching, it's your fault to choose such university.
Oh and "The E", Google came up because of those Math equations. So do some of those Microsoft technologies (Visio, PowerPoint to name few). How about Games??!! Hash function? RSA? Encryption?. Sheez.
Though I full well understand the intent of this article, I saw the TinyMUSH solution and decided to write one up in MUCK Forth.
: tell
me @ swap notify
;
: main
1 begin dup 101 < while
dup 15 % if dup 5 % if dup 3 % if dup intostr else "Fizz" then else "Buzz" then else "FizzBuzz" then tell 1 +
repeat
;
Sub Main()
For n As Single = 1 To 100
Select Case True
Case n Mod 15 = 0
Console.WriteLine("FizzBuzz")
Case n Mod 3 = 0
Console.WriteLine("Fizz")
Case n Mod 5 = 0
Console.WriteLine("Buzz")
Case Else
Console.WriteLine(n)
End Select
Next n
End Sub
Yes, later i see the problem... first must check if it is multiple of 3 and multiple of 5...because if it is multiple of both wend it first check for i%3 it will write just Fizz, there is the right code:
for (int i=0; i<101; i++)
{
if (i%5==0 && i%3==0)//Print if is multiple of 3 AND 5 print
//Fizzbuzz and not the #
{
cout << "Fizzbuzz";
}
else//not multiple of 3 and 5... then print the number
{
if (i%3==0)//Print if is multiple of 3 print Buzz and not the #
{
cout << "Fizz";
}
else//not multiple of 3
{
if (i%5==0)//Print if is multiple of 5 print Buzz and not the #
{
cout << "Buzz";
}
else//not multiple of 5 or 3
{//print the number only if not multiple of 3 anf/or 5
cout << i;
}
}//end if of multiple of 3
}//end if of multiple of 3 and 5
cout<<"\n"; //just endline for every case
}
Thanks... it works for C++, Java or C# just change the COUT lines for the output
Several programmers here have tried the problem, but have produced an incorrect answer. Either they've made an error parsing the problem, or they've not tested their solution to make sure it solves the problem.
Steven Fisher on February 28, 2007 11:59 AMI thought I would try for the most complex solution :)
class CIntegerMod3;
class CIntegerMod5;
class CIntegerMod3andMod5;
class CInteger
{
public:
static CInteger* Create( const int value )
{
CInteger* pInteger = NULL;
if( ( value % 3 == 0 ) && ( value % 5 == 0 ) )
{
pInteger = new CIntegerMod3andMod5( value );
}
else if( value % 3 == 0 )
{
pInteger = new CIntegerMod3( value );
}
else if( value % 5 == 0 )
{
pInteger = new CIntegerMod5( value );
}
else
{
pInteger = new CInteger( value );
}
return pInteger;
}
static void Delete( CInteger* pInteger )
{
if( pInteger )
{
delete pInteger;
}
}
virtual void Print( void ) const
{
cout << m_Value << '\n';
}
protected:
CInteger( const int value )
{
m_Value = value;
}
~CInteger( void )
{
};
int m_Value;
};
class CIntegerMod3 : public CInteger
{
public:
virtual void Print( void ) const
{
cout << "Fizz\n";
}
};
class CIntegerMod5 : public CInteger
{
public:
virtual void Print( void ) const
{
cout << "Buzz\n";
}
};
class CIntegerMod3andMod5 : public CInteger
{
public:
virtual void Print( void ) const
{
cout << "FizzBuzz\n";
}
};
void PrintNumbers( void )
{
for( int i = 0; i <= 100; ++i )
{
CInteger* pInteger = CInteger::Create( i );
if( pInteger )
{
pInteger->Print();
CInteger::Delete( pInteger );
}
}
}
Cheers
Sfx on February 28, 2007 12:29 PM.NET version (minute and thirty seconds):
for (int x = 1; x < 101; x++)
{
bool Wrote = false;
if (x % 3 == 0)
{
Console.Write("Fizz");
Wrote = true;
}
if (x % 5 == 0)
{
Console.Write("Bizz");
Wrote = true;
}
if(!Wrote)
{
Console.Write(x.ToString());
}
Console.Write("\n");
}
Python
for i in range(1, 100) :
fmt = [i, "fizz", "buzz", "fizz buzz"]
print fmt[(i % 3 == 0) + 2 * (i % 5 == 0)]
Stu,
Fortunately, the world doesn't revolve around your personal definitions of words. If you say answering 0x0f + 0x01 is a requirement to meet your definition of a programmer, then in your head it is. The world outside your head goes on without a single thought about who you are or what you believe.
“…how many "great" choices did you pass up [that cannot do FizzBuzz, add 0x0F + 0x01, etc?¨] Not many, that is for sure."
Well, in your case that must be true because you have a personal definition of 'great', and that's just.. uh, GREAT. Some of those people you passed up for not answering 0x10, by law of averages, are probably working on projects just as demanding as your projects if not more so, making much more than you now (assuming you rejected enough candidates). And they STILL don't know HEX and the world doesn't care.
Now, as for not being able to get FizzBuzz down...You're probably on to something there.
globualcluster on February 28, 2007 1:01 PMIt took me 2.5 minutes to flesh out a working fizzbuzz program in C. it took me another 2 minutes to make the program output more elegantly and to learn how to use the modulus operator (%)
The appropriate response, if in interviewing you I ask you to do the FizzBuzz task, is to say (in a loud and clear voice), "Has the customer written the automated acceptance test yet?"
Bill Tozier on February 28, 2007 1:04 PMWhy are you programmers posting solutions? Do you really need to prove yourselves to an anonymous horde that you are in fact number 200, and not number 199? Are you in the top 1% because you can do this ridiculously simple task, or are you in the top 99.9801% as Joel Spolsky points out in his article? I'm thinking it's the latter.
Why on February 28, 2007 1:29 PM@jadawin:
"
Well, since the friend was the test author, and one of the graders, I decided I'd do what it said, and use an obscure language that, pretty much, he was probably the only one to ever have seen; the embedded language in most TinyMUSH-derived games.
@create FizzBuzz
&C-FIZZBUZZ FizzBuzz=$fizzbuzz:@dolist lnum(1,100)=@switch/first 0=mod(##,15),@emit FizzBuzz,mod(##,3),@emit Fizz,mod(##,5),@emit Buzz,@emit ##
"
Dude, (dudette?)
How old are you? That was probably the *LAST* language I expected to see on here. :)
That's pretty much the first language I learned (well, to be fair, I was playing with C at the same time), but I was like 15 or 16 at the time, so in all fairness, it was because it was a game that I got so into it.
I don't recognize the MU* variant, but it's very similar to what I played with.
Thanks for the flashback.
-Samson (my old MU* name)
Samson on February 28, 2007 1:35 PMI like mine in php... you can set the index and how many you want to do.
<?php
//FizzBuzz
Function FizzBuzz($index, $num) {
for($i = $index; $i<=$num; $i++) {
if($i%3==0 && $i%5==0) {
echo "FizzBuzz<br />";
}
else {
if($i%3==0) {
echo "Fizz<br />";
}
elseif($i%5==0) {
echo "Buzz<br />";
}
else {
echo "$i<br />";
}
}
}
}
FizzBuzz(1,100);
?>
I think you are being too idealistic.
Being able to code does NOT make a good programmer?
Its all about resourcing?
http://www.google.com/codesearch
And getting the job done.
a,b = b,a
Ruby rocks :)
bla on February 28, 2007 1:57 PMPrint “1”
Print “2”
Print “Fizz”
Print “4”
Print “Buzz”
Print “Fizz”
Print “7”
Print "8"
Print "Fizz"
Print "10"
Print "Doh!"
Print "Fizz"
Print "13"
Print "14"
Print "FizzBuzz" -- which most peeps above forgot
and so on.
I can't see what the fuss is..
No brainfuck solutions? C'mon guys
ddh on February 28, 2007 2:15 PMI'm sure we've beat this thing to death, but here ya go perl fans:
for (1..100) {print $_ unless (($_ % 3 ? 0 : print "Bizz") || ($_ % 5 ? 0 : print "Fuzz"));}
This blog generated some comments on ISCA BBS, so figured we'd all take a crack at it in our preferred (and not-so-preferred) languages.
Figured I'd post this for perl folks to enjoy. Didn't realize b4 nesting in unless statements was possible like that, but hey...how often are we writing obfuscated code people have to think about to understand? Kind of pointless unless we are trying to tell all the other coders....gee I'm so much l337 than you, you're pathetic (which one wouldn't due in a professional shop anyway).
Jimmy Crackcorn on February 28, 2007 3:37 PMI prefer to ask why can't programmers program tests?
Unit tests are a great test of a programmer/developers skill and I think they should be a requirement for anyone in the modern age.
Why can half of the people here not seem to understand the specs of the prog. Remember its only to test dumb people :P
Mike on February 28, 2007 3:56 PMi'm sick of seeing C/C++ and other {} enclosed solutions so here's my VB6 version. spent less than 5 minutes on it, which is terrible going by other's standards.
dim num as byte, printstr as string
for num=1 to 100
printstr=""
if num mod 3 = 0 then printstr=printstr & "Fizz"
if num mod 5 = 0 then printstr=printstr & "Buzz"
if printstr<>"" then
debug.print printstr
else
debug.print num
end if
next
btw, i'm not proving myself. i'm 18, and i've already tried making a 2d game in VB6. oddly enough, it failed.
all this degrading of other applicants has made me want to apply for a programming job now! still at school for 3 months though.
God, i'm so arrogant.
FWIW, I tried the sample code above using the XOR and OR and it didn't work for a=3 and b=5.
That use of the binary OR leads me to believe that it'll only work for powers of 2. (I.e., using | as a substitute for addition will only work as long as they don't both have the same bits lit up, as 3 and 5 do -- both use the first bit.)
I just tested with a=4 and b=16 and it worked. (Compiling with g++)
Is there a version of this that works with numbers that aren't powers of 2?
To the perl 1 liner author:
for (1..100) {print $_ unless (($_ % 3 ? 0 : print "Bizz") || ($_ % 5 ? 0 : print "Fuzz"));}
When you hit multiples of 3 and 5, it doesn't print BizzFuzz. Nice try though.
Ivan on February 28, 2007 4:58 PMPlain C:
int i;
for (i = 0; i <= 100 ; i++) {
if ((i % 3 == 0) && (i % 5 == 0))
printf("FizzBuzz\n");
else if (i % 3 == 0)
printf("Fizz\n");
else if (i % 5 == 0)
printf("Buzz\n");
else printf("%d\n", i);
}
I think that one word/number per line is more readable for such a useful piece of software... ;-)
78 chars:
perl -le'print$_%15==0?"FizzBuff":$_%3==0?"Fizz":$_%5==0?"Buzz":$_ for 1..100'
Using naughty syntax we can get it down to 72 chars:
perl -le'print$_%15==0?FizzBuff:$_%3==0?Fizz:$_%5==0?Buzz:$_ for 1..100'
Here's the same program with sane indenting: http://rafb.net/p/QLtUvx47.html
example output:
1
2
Fizz
4
Buzz
Fizz
...
FizzBuff
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
__END__
Long live recreational QBasic programming!
FOR i = 1 TO 100
q = 0
p = 0
IF i / 3 = INT(i / 3) THEN
IF i / 5 = INT(i / 5) THEN
PRINT "FizzBuzz"
q = 1
END IF
IF q = 0 THEN PRINT "Fizz"
p = 1
END IF
IF i / 5 = INT(i / 5) THEN
IF p = 0 THEN PRINT "Buzz"
p = 1
END IF
IF p = 0 THEN PRINT i
NEXT i
***This is the stuff that real programming is made of!
[RANT]
I hate it when I see people learning Visual Basic. It's just so wrong. When I see people trying to figure out to throw an exception, I just shiver! It's like they miss the whole point of programming in the first place. The point of programming, FYI, is to make a function or group of functions which does something useful.
In my spare time I have created a few QBasic programs which do things like estimate the sine of a value from an infinite sum of square wave, calculate the power in the sine wave harmonics of a square wave, map points in 3d space to points in 2d space (like a graphics card), rotate a four-dimensional object, etc. I've also made (well mostly attempted to make) a few neural nets. This is all useful (or at least the type of stuff that could be useful). Making arrays defining functions are all useful things for everything I have done.
I don't see why exceptions are useful. They are just one of those unimportant, un-needed things that "programmers" learn about.
I personally like to handle every possibility personally in my programs and use deep thought to figure out how to map a particular set of inputs to the desired set of outputs. The VB programmers I know just don't seem to be that involved in what they are doing. They use VB like they would use Excel. Do you know what I'm saying?
[/RANT]
For the people that said the XOR trick would only work for integers... thats not entirely true...
It will work for characters as a single character in memory is really an integer in most languages. For strings you just have to break it down into a character array and use a loop (do/while looking for the null character '\0' at the end of the character array.
Also because of this, if you do actual memory swaps using this method it should be possible to do any other datatype/structure/object though you have to be using a language that will allow you to directly manage the memory.
And for the people that don't know the XOR trick (and can't look things up on Google..)
http://en.wikipedia.org/wiki/XOR_swap_algorithm
// Here's my attempt at an elegant C(++) solution.
// I'll assume the appropriate headers are included.
// This snippet can be put into main or elsewhere.
// I'm a bit rusty with the details, as I haven't
// C++'ed in years.
#DEFINE FACTOR0 3 // Using macros for easier portability to other
#DEFINE STRING0 "Fizz" // uses, without increasing code size, memory
#DEFINE FACTOR1 5 // needs, or decreasing performance.
#DEFINE STRING1 "Buzz"
for(int i=1; i<=100; i++;)
{if(!(i%FACTOR0)) printf(STRING0);
elseif(!(i%FACTOR1)) printf(STRING1);
else printf("%i", i);
printf("\n");}
Spencer asked "Does anyone have a link to more programming exercises that I could do?".
Check out www.projecteuler.net - The problems posted there require short programs but most also require a lot of thought. Depending on the language you use, you might have to borrow or write your own large integer class.
FredJ on February 28, 2007 7:03 PMMethod with one less if statement since 3 and 5 aren't mutually exclusive and variable names.
void main()
{
for (int i = 1; i <= 100; i++)
{
bool isdiv3 = !(i % 3);
bool isdiv5 = !(i % 5);
if (isdiv3) cout << "Fizz";
if (isdiv5) cout << "Buzz";
if (!(isdiv3 || isdiv5)) cout << i;
cout << "\n";
}
}
Speaking as a newly hired entry-level programmer, I think this post is completely ridiculous. I wasn't able to answer your FizzBuzz question very quickly (although the logic of it was obvious), but I was recently hired by the IT division of a top I-banking company anyway. What's more, I don't think they cared if I could code that well yet. What's more than more, I think they were correct not to.
I'll be honest, I didn't think I would get the job. I'm not even a CS major (Math major, CS minor). But they hired me because I'm smart and demonstrably trainable, and have passions outside academia. Basically, I represent a low risk. They can train me however they need to and feel comfortable in the belief that I will be able to contribute. But the fact that they have to train me is not my fault. Schools don't teach students how to code anymore, don't you all know that? How can an institution like that keep up with all the changes in programming that happen so, so fast. Do you know how much php, ajax, C, C++, perl, FORTRAN, COBOL, or Ruby I was taught? None, nada, zilch. It was "on me" to learn these languages if I needed them for an assignment, which was rare. The only thing I was taught was Java, and not very much of it.
However, what I WAS taught was theory and architecture. Heaps, stacks, linked-lists, graphs, hash-tables, classes, inheritence, search trees, Big-O, min-cuts/max-flows, database management, logic and set-theory, optimization, and all the basics of data architecture. Hell, I know more Assembly than I do C++!
This knowledge spans all disciplines within computer science and any language. I might've gotten a job designing websites for a 2.0 or helping to manage a database for a bank. There's just no way to know how I was to focus my college studies, so I was given the big picture instead. I think this will work, I'll find out for sure soon enough.
Java:
String s[] = {null,null,"Fizz",null,"Buzz","Fizz",null,null,"Fizz","Buzz",null,"Fizz",null,null,"FizzBuzz"};
int i = 0;
for (int count = 1; count <=100; count++)
{
if (i < 15)
{
if (s[i] == null)
System.out.println(count);
else
System.out.println(s[i]);
}
else
i = 0;
i++;
}
The question I asked many candidates was
Write a function to test if the argument is part of the Fibonacci sequence.
Many candidates don't know where to start.
But not 199 out of 200.
Is HR not screening anyone out for you?
tim dugan on February 28, 2007 9:07 PMAt our dept. special attention was paid to developing logic than learning any specific coding language. Most of the times we had to choose the language for the given assignments and also had to give explain why it and not any other, during our assignment reviews. During my degree i used to get frustrated thinking that my friends in other colleges/universities were already talking in C#, ASP.NET and all that stuff. But now i understand the value of it. Languages can be learnt easily, what takes time is developing logic. Thats what universities must focus on & not on give new technology specialists. Such candidates usually find it hard to get adapted to new things.
Eros on February 28, 2007 9:28 PMI'm a completely self-taught programmer in high school (with a job as a programmer as well), and sadly this is something even I've observed in my limited scope. It really is scary when the company I work with is trying to hire guys who know less than the autodidact twelfth grader with only five-years experience. I could write this program with 5 languages in probably 10 minutes total. Heck, I could even add a Windows GUI with API for the C++ version with another ten minutes. It's only too sad this is not true for those graduates with supposed 'degrees.' According to the ever-wise Carlos Mencia: "Let's lower the standards!"
Cameron B on February 28, 2007 9:29 PMI am a self-taught programmer. I started out programming batch scripts in Windows 3.1. After that I dabbled in HTML 2.0. THen i was introduced to Borland C, and from there became aware of assembly language. Assembly language became my hobby for a while. I've written over 3000 lines of assembly code, hand-coding any libraries I needed. Unfortunately, I didn't think to look on SourceForge for free 32-bit assemblers. So here I am in the era of 64-bit multithreaded-multicore processing and I'm fluent in only Batch script, assembly for the 80286, and DOS-mode C. Learn from my mistakes people, and if you;re a programmer, take every effort to stay on the cutting edge.
Blake Escritt on February 28, 2007 9:41 PMI really find it unbelievable that the fizzbuzz program is so difficult for so many people. I graduated college with a BS in computer science about 6 months ago and found this to be very easy to write. I cannot imagine any other students that I graduated with having any difficulty solving it. However the point that many graduates are poor programmers is definately true. I noticed many of my fellow students having trouble with simple programs, its very common.
JR on February 28, 2007 9:47 PMHey Jeff,
I work for Vertigo too. I'm technically a designer, though I use PHP, Python, Ruby, JavaScript, and have used Bash, Awk, Sed and Tcl for work in the past. Not sure if that defines me as a designer or programmer. Anyway, here's how I'd do the variable swap thingie in JavaScript:
function swapVars(){
x = 10;
y = 2;
x = x ^ y;
y = x ^ y;
x = x ^ y;
alert("x did = "+y+" and y did ="+x+", but now x = "+x+" and y = "+y);
}
window.onload=swapVars;
And here's the FizzBuzz in JavaScript:
function fizzBuzz(){
var i = 1;
while ( i < 100 ) {
alert(i%3==0&&i%5==0?"FizzBuzz":i%3==0?"Fizz":i%5==0?"Buzz":i);
i++;
}
}
window.onload=fizzBuzz;
(By the way, because a browser window can have only one window.onload event, you'd need to try each one separately, comment out the other, unless you use a function to queu them.)
I am a self-taught programmer. I started out programming batch scripts in Windows 3.1. After that I dabbled in HTML 2.0. THen i was introduced to Borland C, and from there became aware of assembly language. Assembly language became my hobby for a while. I've written over 3000 lines of assembly code, hand-coding any libraries I needed. Unfortunately, I didn't think to look on SourceForge for free 32-bit assemblers. So here I am in the era of 64-bit multithreaded-multicore processing and I'm fluent in only Batch script, assembly for the 80286, and DOS-mode C. Learn from my mistakes people, and if you;re a programmer, take every effort to stay on the cutting edge.
Blake Escritt on February 28, 2007 9:55 PM@Robert Biggs
I will say designer more then programmer. I kindly ask that you not force me to press ENTER 100 times. Thanks! :D
I have met a lot of programmers who just suck. However, I don't think you can weed them out through simple tests or pedantic questions. In fact, I have seen where really good programmers are either weeded out or just get pissed off at the wasted time and go someplace else.
For example, I went to two job interview where they asked me questions like, "How could you tell if a binary file was a compiled Java file or not?" I said I didn't know. They said, that you could tell because the first few bytes in a compiled Java file say some phrase like "Hot Java" or something.
First of all, who the hell cares? And secondly, as a programmer at your company, am I going to spend significant amounts of time looking for hidden messages in compiled Java files? If so, you can hire somebody else.
While I use recursion regularly in code to search a directory tree for specific file-types that I want to parse, I can understand that many good programmers have had no need for recursion. I can teach a good programmer to write recursive code, so why would I want to throw them out just because they haven't ever had to write it before?
I do like the FizzBizz test though. It is simple and any coder should be able to figure out a way to make that happen.
Clinton on February 28, 2007 10:13 PMOops! Just noticed that my FizBuzz example only goes to 99
It's late and I'm recovering from stomach flu, blahhh!
The while loop should be:
while ( i < 101 ) {
Yikes! Forgot the blog filters out html tags. This should work:
<script>
function fizzBuzz(){
var i = 1;
while ( i < 101 ) {
document.write(i%3==0&&i%5==0?"FizzBuzz"+"<br>":i%3==0?"Fizz"+"<br>":i%5==0?"Buzz"+"<br>":i+"<br>";
i++;
}
}
window.onload=fizzBuzz;
</script>
I couldn't resist either....
SQL query (Oracle):
WITH A AS (SELECT * FROM DUAL UNION ALL SELECT * FROM DUAL),
B AS (SELECT A.* FROM A, A A2 UNION ALL SELECT * FROM DUAL)
SELECT CASE WHEN MOD(ROWNUM, 15) = 0 THEN 'FizzBuzz'
WHEN MOD(ROWNUM, 5) = 0 THEN 'Buzz'
WHEN MOD(ROWNUM, 3) = 0 THEN 'Fizz'
ELSE TO_CHAR(ROWNUM) END FROM A, A A2, B, B B2;
In Groovy, 70 chars:
(1..100).each{println it%3&&it%5?it:(it%3?'':'Fizz')+(it%5?'':'Buzz')}
To find all ways you can swap two variables in three moves without using a temp:
def x=[4,13], y=[13,4], z=[] as Set
def c=[
[ { [it[0], it[0]&it[1]] }, 'b=a&b'],
[ { [it[0], it[0]|it[1]] }, 'b=a|b'],
[ { [it[0], it[0]^it[1]] }, 'b=a^b'],
[ { [it[0]&it[1], it[1]] }, 'a=a&b'],
[ { [it[0]|it[1], it[1]] }, 'a=a|b'],
[ { [it[0]^it[1], it[1]] }, 'a=a^b'],
]
c.each{f-> c.each{g-> c.each{h->
if( h[0](g[0](f[0](x))) == y ) z<< f[1] +'; '+ g[1] +'; '+ h[1]
}}}
assert z==[
'a=a^b; b=a^b; a=a|b',
'a=a^b; b=a^b; a=a^b',
'b=a^b; a=a|b; b=a^b',
'b=a^b; a=a^b; b=a^b',
] as Set
| Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved. |