- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
No doubt everyone will point out how hideous this code is. But it at least demonstrates how you don't have to test for fizbuz explicitly. Is bash shell.
j=0; for i in {1..100}; do if [
expr $i % 3
= 0 ] ; then echo -n fiz ; else j=expr $j + 1
; fi; if [expr $i % 5
= 0 ] ; then echo -n buzz; else j=expr $j + 1
; fi; if [ $j = 2 ] ; then echo -n $i; fi; echo; j=0; doneAdmin
Thanks for the info.
As for stdio, I coded this in 2 minutes and didn't feel like looking up whether or not I actually needed stdio, or whether or not it had a .h. As for hungarian notation, I have no idea what the hell that is. And I did use \n instead of endl, unless you meant it the other way around, in which case I've got nothing. I just hate using endl. Remember C++ compilers account for the newline/carriage return controversy.
In conclusion, if anything, this is merely further proof it's a bad idea to ask high school students with only a fundamental grasp of programming to do work for you ;)
Admin
If the text was "The dog went grrrowl" and the search string was "rr". How many times would you find it?
Admin
Just to make everybody happy, here's FizBuz, written concisely in Scheme with an iteration construct.
It uses three tests. But it's clear about what it's doing.
Now what you should be doing is playing the advanced Buz game. Print "Buz" instead of the number if the number is a multiple of 7 or has a 7 digit in it. Good times.
Admin
Admin
Gentlemen, I hereby present The Real WTF.
Admin
Admin
this is knocked down to minimal space. execution-wise I would set up the lenths as values instead of recalcing each iteration....
Admin
Filter this with sort -n:
Admin
For the heck of it, here's a python version with a for-break-else loop.
TRWTF is those who questioned why the index starts with 1 instead of 0. You gotta read the requirement more carefully -- there's a space at the beginning of the input text :P
Admin
Honestly if you are re-implementing Boyer-Moore from scratch for an interview question then either you or the interviewer is doing it wrong.
Admin
I wouldn't assume that the subtext cannot contain spaces.
Admin
I think part of the point of 'find substrings' is that the names of all those predefines convenience functions are actually taking up more of your brain cells than their implementation:
int rchar(char *str, char c){ int j= 0; char *s= str; while(*s) if(*s++==c) j= s-str; return j-1; }
Or is it called lastCharOf? or RChar? Whee--how many lost brain cells? Are you a programmer or a fukin dictionary?
Admin
Uhmmm, WHAT? What do spaces and tokens have to do with anything?
You are given two strings A and B. Find all of the occurences of B in A.
Any good programmer can sit down and write the program in a few minutes. Sure its reinventing the wheel, but guess what you've got a short amount of time to interview. Reinvent.
If I asked that question, and got a response about spaces and tokens, I'd say "No Hire."
By the way, I used to ask people strcmp. I got about %10 success rate with <1% writing it like K&R.
Admin
Hey guys, I 'rm -rf /'ed instead of 'rm -rf ./', how do I undo it?
plz send me teh codez.
Admin
I thought the answer is: "1st, you take a measuring tape..." you get the idea ;-)
Admin
Maybe I've been too much maths recently, but I would have understood that to be about abritrary points in an arbitary space. I would have said something along the lines of:
"I'd use a sensible metric function for the space and evaluate it for the two points. If they're simply points in a Euclidian space, then the metric is the square root of the sum of the squared difference for each ordinate. In a Manhattan space, then the metric is the sum of the absolute difference for each ordinate. It gets a little more interesting if they're points on the surface of a sphere or a torus or something."
Admin
private char myToLower(char c) { return (char) (c | 0x20); }
??
Admin
C. Personally, I only use 2 tests (:
for ( i = 1 i <= 100; i++ ) { printf ( "%d: ", $i ); if ( ! (i % 3)) { puts ( "Fiz" ); } if ( ! (i % 5)) { puts ( "Buz" ); } putc ( '\n'); }
Admin
You're all fired. 2 comparisons worst case. ZERO division or modulo operators. 1/3 as many cycles in the loop. Example code that does the same thing using the lame way available below for comparison.
Admin
Correct. Since the spec says not to use String methods, it is required to write your own code for lowering the case of a letter (if that is part of your solution). Hence this method which would be combined with a loop through a char[] representing the input string. As others have already posted the code for the loop, I didn't feel the need to repeat that part.
Admin
try it...
Admin
Said the guy on TheDailyWTF.
Admin
Here's my solution in PHP; probably slow and it uses recursion, but since this the question is basically "build a simple regular expression matcher," recursion is nice.
Admin
I'm in agreement, it seems pointless to me too. When looking for good developers, having someone prove they can "do things the wrong way" is simply less effective than having someone provide a positive demonstration of their ability.
I have the same disregard for interview techniques such as riddles (as distinct from being asked to solve a genuine, practical problems), the specific meaning or behavior of truly obscure protocol errors or methods (from memory) and the ability demonstrate a telepathic ability / hive mind - as required when it is deemed necessary to guess specific answer the interviewer is looking for ("Okay then, so those are 3 valid ways of doing it you've just mentioned, but what if you couldn't do any of them then how would you do it? No - that wasn't the one I was thinking of either, try again.").
I was looking around London about a year ago and enquired three positions, at a range of different companies. No interviewer bothered to check out open source software I've written or checkout my svn repository or any of my previous work in any way (even though I'd email links ahead encouraging them to do so, and all the had to do was click on them to see some examples).
Purely theoretical exercises, riddles, buzzword bingo, pretending to be "more-agile-than-thou" and all seem to be vogue.
Perhaps it's just me, but here in London in particular there seems to be an abundance of developers who can give all the right responses to academic maths questions, say all the right things about "how agile they are", get all the latest buzzwords right and name drop the flavor-of-the-month languages and frameworks, but can't actually write decent[0] software at the end of the day (and often require a large team of developers to even attempt anything, even when they are writing fairly straightforward software).
[0] i.e. That is (broadly) scalable, straight forward to maintain, cross platform, standards compliant, written in an appropriate language (etc). I've heard those things described as "too obvious" to be worth enquiring about, even by teams who I know have fundamental issues with those very problems.
Admin
That's nice but it doesn't actually solve the problem because you printed out the numbers even when you printed Fiz or Buz.
Have a look here: http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/. You see that TRWTF all along was that some of us knew what the customer wanted (have the computer play the Buzz game), and some of us only knew what the customer told us (for values of customer equal to Sad Bug Killer -- see Page 1 of the comments).
This is hard to do with just two tests in C, but being able to overwrite the value of the number helps. See below:
This may be premature, but I think I win.
Admin
Admin
At first I wrote this function in C, but someone told me that it was not correct since I did not implement Knuth Morris Pratt algorithm, that pissed me off because that was not the task, but when i noticed that "hellohello" for the context "hellohellohello" returned 1, i just had to redo it, however, since this task was for C#, where you can compare strings using the == operator, I rewrote it in PHP which is pretty much the same thing as C#.
Admin
Huh? Common Lisp provides a fairly complex and slightly under-specified iteration powerhouse known as do. The example in the tutorial is only a tip of the iceberg: http://www.n-a-n-o.com/lisp/cmucl-tutorials/LISP-tutorial-18.html
Admin
I wouldn't hire ANY of you. The only requirement was that you not use any of the built-in string functions, but it never said you could not use any of the builtin Regular Expression functions. Here's a WORKING (yes, actually tested) example.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions;
namespace TestParser { class Program { static void Main( string[] args ) { string text = "Polly put the kettle on, polly put the kettle on, polly put the kettle on we'll all have tea"; RunParser( text, "Polly" ); RunParser( text, "polly" ); RunParser( text, "ll" ); RunParser( text, "x" ); RunParser( text, "Polx" ); Console.ReadKey(); }
}
Admin
must...not...implement...fizzbuzz...either...damn.
Example in Clean:
That's the whole, compilable program. "lcm" is least common multiple, "Start" is the equivalent of the "main" function, "map", as in Python, Haskell, &c, means "apply this here function to every element of this here list."Despite appearances this code is completely statically type-checked by the compiler.
That's the sum total of my Clean coding to date. Took 15 minutes, including checking the book for all the keywords and standard functions. Probably an experienced Clean coder could do it in one line, without the guards ("|").
By the way, Fizzbuzz is example 1-2 in David Flanagan's Java Examples in a Nutshell, O'Reilly 1997. Yup... right after "Hello, world!".
Admin
the correct answer is
"with a ruler"
Admin
Admin
No, Joe. You're fired. Professional programming is about communicating with other programmers. (Since you're a professional, it can be taken for granted that you can get the computer to do what you want.)
Master coders all advise you to do things the simple, obvious, easily understood way, unless there is an overwhelming reason to do something different... in which case, you document the reason and the algorithm, provide copious hints for the maintainer, including asserts and invariants, and provide references to standard texts that will assist the maintainer.
This is a courtesy from one professional to another: it saves the reader's time.
My own experience both as a maintainer of other people's code, and as a supervisor of people maintaining my code, bears out what I have read... doing what they say does save time. And therefore money.
Your code fails on all counts. It's not the code of a professional.
Admin
You still have 3 tests, and your code takes twice as long to read and be confident about than the "naive" code. See my reply to Joe Bruin.
Please, coders: professional coding is writing for people. Time-poor people. Write to be understood as easily as possible.
Admin
The real WTF is that interviewers continue to ask for nonsense, toy code snippets in interviews, and think this is the proper way to gauge if a candidate is a good coder. Being an uber-geek and knowing how to solve this FizzBuzz crap doesn't make you a good developer - creating working software that does what it's intended to do and helps the business you work for is.
Admin
Yeah but that is a very ineffective way of doing it, consider doing that test in the bible - you would spend a lot of time and memory since you need to contain all words split in memory - and you are at a minimum passing through the whole set of strings twice (once to make them, once to test).
There are some very effective string searching algorithms running in N+M which also only uses up N+M bytes of memory + a few pointers - it can even be modified to only read a byte from M at a time cutting the memory usage down to N+1+pointers. (Not a C# programmer, don't know how close to memory you can get) On top of that with minor modifications you can search for multiple words in a single pass.
Oh and the poor guy who send a delete with no where clause, oh my. Guess most cowboy programmers have tried that - which is why no one is allowed to execute embedded SQL here.
Admin
I'd give them a FizBuz solution in BeFunge, just to annoy them:
yes, it works. yes, I am bored at work ;)
Admin
Oh, this is too good to pass on. I can't remember which of the dozen or so interviews I had in London last year gave me this test, so 'MonkeyCode' can rest assured I'm not going to blow his cover.
What I -will- say is that I spent an hour writing a solution for this problem, including full comments to explain what I was doing, how it worked, and even what built-in methods I'd use in preference in The Real World. It did exactly as asked in terms of output generation, and even had a bit of basic validation in there to prevent exceptions due to empty string inputs, etc.
It was basic stuff, amounting to maybe 25-30 lines of code (including comments) but it did the job exactly as specified and was fairly bullet-proof to boot. I got a response about a week later. I forget the exact wording, but the essence of it made me laugh out loud and think of TDWTF.
My solution was 'not enterprise-y enough'.
Admin
Not sure if anyone else has mentioned this... but there is a difference between '\n' and endl that it seems you're missing. endl flushes the buffer being written to, '\n' doesn't.
Admin
A Python example of FizBuz using objects:
class Fiz(object): def init(self, number): self.number = number def check(self): return self.number % 3 == 0
class Buz(object): def init(self, number): self.number = number def check(self): return self.number % 5 == 0
for i in range(1,101): out = '' fiz = Fiz(i) buz = Buz(i) if fiz.check() == True: out += 'Fiz' if buz.check() == True: out += 'Buz' if out == '': out = str(i) print "%s" % out
And to the guy claiming there's only two comparisons needed, he's flat out wrong. There are four test cases (is % 3, is % 5, is both, is neither). Just because you can easily combine two or more of them into a single test doesn't mean the test cases don't still exist.
Admin
fizzbuzz n=head$filter(not.null)[concat[s|(s,d)<-[("Fizz",3),("Buzz",5)],mod n d==0],show n]
Couldn't resist writing an obfuscated Haskell fizzbuzz.
Admin
I wouldn't hire you either, for deliberate and malicious over-engineering and willful under-use of ternary operators:
Admin
London being a world city, I'd think you'd have the cream of the crop available.
This was probably anonymized, but presumably from a comparable city. I wouldn't think that in any similar city you'd have trouble.
Admin
This was tested to work under C-INTERCAL 0.28 (open-source, download available from http://intercal.freeshell.org/); incidentally, it exposes a bug in C-INTERCAL 0.26, so a newer version than that is needed. A CLC-INTERCAL version would be significantly more complicated (but easier to make case-insensitive).
Oh, and if anyone here is insane enough to ask me how it works, I'd be delighted to answer. This code is confusingly written even by INTERCAL standards...
Admin
If we're talking about physical points, it would require us to define the observer position and speed as well... relativity, you know.
Admin
If you're going to answer "with a ruler", you have to prefix it with "given a ruler whose number of dimensions are more than or equal to the number of dimensions of the points"... Actually, scratch that. It assumes that the two points have an equal number of dimensions.
Admin
If asked to do this in the interview, I'd first tell them that I'm going to write this as if I had no restrictions on using the String methods to use as a template. So, I might end up with something like so:
private static void Search( string stringToSearch , string searchString , int startIndex, ICollection<string> foundIndexes ) { int index = stringToSearch.IndexOf( searchString , startIndex , StringComparison.CurrentCultureIgnoreCase ); if ( index == -1 ) return; foundIndexes.Add( index.ToString() );
}
Then I'd tell the interviewer that if they really wanted the equivalent routine without the use of String methods, to give me Reflector and I'll implement the equivalent of Length and IndexOf using their core implementation. If displeased with that, I'd retort, "Hey, why stop there? Why not require that I write my own compiler? Why not preclude the use loops or recursion? Why let me use those funny parentheses and commas?"
Sometimes interviewers try to be too clever for their own good. If you really want to test someone's ability, the right solution is to come up with a reasonable test. One company with whom I consulted actually created a small project for interviewees. They asked the candidate to build a simple ASP.NET form that had to talk to three or four tables with a many-many relationship. They gave them a workstation with access to the Internet so they could dig up any information they wanted. In addition, they kept a few of the specs intentionally vague and told the developer that at any time they could ask the interviewer for clarity. It was amazing how many failed miserably. Many spun their wheels and never asked for clarity. Many couldn't even get past opening Visual Studio.
Admin
Sounds to me like Paula Bean is out on the prowl again. Please send me teh brillant codez.
Admin
How about:
And of course run that in a loop.
You could also create a table with cached values. The real issue is what it would be used for in real life.