Forum: Ruby FizzBuzz (#126)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
James G. (Guest)
on 2007-06-01 16:28
(Received via mailing list)
The three rules of Ruby Q.:

1.  Please do not post any solutions or spoiler discussion for this quiz
until
48 hours have passed from the time on this message.

2.  Support Ruby Q. by submitting ideas as often as you can:

http://www.rubyquiz.com/

3.  Enjoy!

Suggestion:  A [QUIZ] in the subject of emails about the problem helps
everyone
on Ruby T. follow the discussion.  Please reply to the original quiz
message,
if you can.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

There has been some debate on the proper ways to screen programmers you
intend
to hire.  A common theory is that you really need to have the programmer
write
some code for you to accurately gauge their skill.  Exactly what to have
them
write is another debate, but the blogosphere has recently been abuzz
with this
question as a screener:

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

Pretend you've just walked into a job interview and been hit with this
question.
Solve it as you would under such circumstances for this week's Ruby
Quiz.
unknown (Guest)
on 2007-06-01 17:35
(Received via mailing list)
In message
<removed_email_address@domain.invalid>,
Ruby Q. wri
tes:
>  print “FizzBuzz”.
>
>Pretend you've just walked into a job interview and been hit with this question.
>Solve it as you would under such circumstances for this week's Ruby Q..

For extra fun, try to do it so the core loop is:

(1..100).each { |x| p x }

-s
Hans F. (Guest)
on 2007-06-01 17:56
(Received via mailing list)
Ruby Q. wrote:

>   print “FizzBuzz”.
>
> Pretend you've just walked into a job interview and been hit with this question.
> Solve it as you would under such circumstances for this week's Ruby Q..
>

Done, 4 times over. Not a bad quiz though my answers will probably be
considered boring and would be denounced by the fools using this tactic
to hire people as "unimaginative" or "lacking creativity and whizbang
problem-solving skills".

I feel compelled to point out that it was Microsoft who started this
whole mess, and they quickly figured out it was selecting the wrong
people and they don't do it anymore. But the cat's out of the bag, and
now every wannabe shop thinks that's the way to find smart people. It's
not, it's the way to find people who are good at solving puzzles under
pressure, and in the worst case to find people who are good at finding
ridiculously clever (but unreadable/unmaintainable) answers to puzzles
under pressure.

As we all know, good software development is not about solving little
puzzles. It's about reasoning about problems large and small and finding
the most obvious and readable solution (and sometimes optimizing the
inner loop).

Maybe I would try this in a job interview. I might state the problem and
say: "this is not a trick question nor hard - just write the code they
way you normally would." If they write the boring answer, they get
points in my book. If they write some clever answer, they get demerits.
If they can't write code at all, and I didn't realize they wouldn't be
able to, I go sit in a corner and pout.
Paul N. (Guest)
on 2007-06-01 18:11
(Received via mailing list)
On Jun 1, 9:51 am, Hans F. <removed_email_address@domain.invalid> wrote:
> >    numbers which are multiples of both three and five
> I feel compelled to point out that it was Microsoft who started this
> the most obvious and readable solution (and sometimes optimizing the
> inner loop).
>
> Maybe I would try this in a job interview. I might state the problem and
> say: "this is not a trick question nor hard - just write the code they
> way you normally would." If they write the boring answer, they get
> points in my book. If they write some clever answer, they get demerits.
> If they can't write code at all, and I didn't realize they wouldn't be
> able to, I go sit in a corner and pout.

I do not think there is a lot of room for cleverness in the FizzBuzz
problem.  (Actually, I hope I am wrong and we see lots more
suggestions for Extra Fun like Peter's.)  My understanding is that
FizzBuzz was intended to screen out candidates that could *not* come
up with working code in a few minutes.

Regards,

Paul.
unknown (Guest)
on 2007-06-01 18:19
(Received via mailing list)
In message <removed_email_address@domain.invalid>, Paul
Novak writes:
>I do not think there is a lot of room for cleverness in the FizzBuzz
>problem.  (Actually, I hope I am wrong and we see lots more
>suggestions for Extra Fun like Peter's.)  My understanding is that
>FizzBuzz was intended to screen out candidates that could *not* come
>up with working code in a few minutes.

It took me a good twenty minutes, but then, I'm a total newbie at Ruby,
and I made about 5 different mistakes.  I mean, it took me a while to
even figure out ... Oh.  You know, I'm gonna have a hard time saying
what
was hard about it for me without spoilers, huh.

I do have it working, though.  The idea was obvious, the implementation
slightly less so, and I'm Probably Doing It Wrong.

-s
Thomas W. (Guest)
on 2007-06-01 18:24
(Received via mailing list)
Fizzbuzz has nothing with the Microsoft "How many Ping Pong balls fit
in a Jumbojet" questions. It got a lot of feedback at
http://www.codinghorror.com/blog/archives/000781.html .
Another one used it to find out if CS graduates can program.

2007/6/1, Hans F. <removed_email_address@domain.invalid>:
Todd B. (Guest)
on 2007-06-01 18:27
(Received via mailing list)
On 6/1/07, Paul N. <removed_email_address@domain.invalid> wrote:

>
> I do not think there is a lot of room for cleverness in the FizzBuzz
> problem.  (Actually, I hope I am wrong and we see lots more
> suggestions for Extra Fun like Peter's.)  My understanding is that
> FizzBuzz was intended to screen out candidates that could *not* come
> up with working code in a few minutes.
>
> Regards,
>
> Paul.



Immediately coming up with something terribly clever was admittedly my
first
instinct when reading the quiz description.  After a few minutes, I
realized
that I'd probably be handing the interviewer no solution at all.  I'm
that
type of person; have it work exceptionally well (on all levels), or
don't
bother.  Perhaps it's a test of personality more than one of performance
under pressure.

Todd
Robert D. (Guest)
on 2007-06-01 18:35
(Received via mailing list)
On 6/1/07, Todd B. <removed_email_address@domain.invalid> wrote:
> On 6/1/07, Paul N. <removed_email_address@domain.invalid> wrote:
>
> >
> > I do not think there is a lot of room for cleverness in the FizzBuzz
> > problem.  (Actually, I hope I am wrong and we see lots more
> > suggestions for Extra Fun like Peter's.)  My understanding is that
> > FizzBuzz was intended to screen out candidates that could *not* come
> > up with working code in a few minutes.
Me too I consider this a very good psychological quiz.
My solution is ready and it was a compromise between being clever,
liking the code I have written and *maybe* getting the job.
Given that it took me almost 10 minutes to find that compromise and I
am really looking forward to getting some feedback about the
impression such a solution would make.
James do you have some surprise for us like interpretation from
recruiters?

This is an odd looking quiz but I guess it might become one of the
most interesting ones, actually it already is, given this discussion
;)

Cheers
Robert
James G. (Guest)
on 2007-06-01 18:37
(Received via mailing list)
On Jun 1, 2007, at 9:25 AM, Todd B. wrote:

> Perhaps it's a test of personality more than one of performance
> under pressure.

I happen to agree and I worded the quiz very carefully with that in
mind.

James Edward G. II
James G. (Guest)
on 2007-06-01 18:39
(Received via mailing list)
On Jun 1, 2007, at 9:34 AM, Robert D. wrote:

> James do you have some surprise for us like interpretation from
> recruiters?

I think we're already getting plenty of insightful interpretation.

James Edward G. II
unknown (Guest)
on 2007-06-01 18:53
(Received via mailing list)
In message
<removed_email_address@domain.invalid>, "Thomas
Wieczorek" wr
ites:
>Fizzbuzz has nothing with the Microsoft "How many Ping Pong balls fit
>in a Jumbojet" questions. It got a lot of feedback at
>http://www.codinghorror.com/blog/archives/000781.html .
>Another one used it to find out if CS graduates can program.

What scares me about that page is the number of incorrect answers
in the comments.  Yeesh.  I might or might not have gotten it on the
first try even doing it sanely, but certainly, I would have TESTED
my code before suggesting that I'd solved the problem.

-s
James G. (Guest)
on 2007-06-01 19:13
(Received via mailing list)
On Jun 1, 2007, at 8:55 AM, Hans F. wrote:

>> question as a screener:
> Done, 4 times over.
I almost didn't run it, for this reason.  Solutions are everywhere,
even in Ruby.

I do think it's an interesting problem though, more because of what
it's looking for (whatever you believe that is) than the code.  I
think how you solve it is important.

James Edward G. II
Hans F. (Guest)
on 2007-06-01 20:26
(Received via mailing list)
James Edward G. II wrote:

>> Done, 4 times over.
>
> I almost didn't run it, for this reason.  Solutions are everywhere, even
> in Ruby.

Oh, I meant I had done it in four ways since the quiz had been posted.

Re the comment about not being one of the ping pong balls in a jumbo jet
questions, that's true.

Having not heard of this particular problem, I jumped to the conclusion
that it was one of those "write this seemingly simple program but you're
not cool unless you do it the clever way I'm thinking of" problems. If
it's really used as just a "can you write a simple program" question,
I'm all for that.
Giles B. (Guest)
on 2007-06-01 20:33
(Received via mailing list)
> I do not think there is a lot of room for cleverness in the FizzBuzz
> problem.  (Actually, I hope I am wrong and we see lots more
> suggestions for Extra Fun like Peter's.)  My understanding is that
> FizzBuzz was intended to screen out candidates that could *not* come
> up with working code in a few minutes.

I have the exact same understanding about the intention of FizzBuzz,
but I disagree about the lack of room for cleverness. I've seen it
solved with lazy evaluation and with a Lisp interpreter that ran a
Prolog interpreter (both solutions were written in Ruby).

I've even seen it **unit tested**. (That solution was in Java.)

I wrote some pretty cranky anti-FizzBuzz blog posts a while ago but
still succumbed to the peer pressure and wrote my own (which contains
a small amount of unnecessary code which I didn't spot at the time).

Won't post til the quiz deadline, of course, but just wanted to say, I
think there's a lot of room for cleverness here, although I sometimes
think the clever solutions are a bit perverted in the brainpan.

--
Giles B.

Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org
Daniel M. (Guest)
on 2007-06-01 21:27
(Received via mailing list)
Hans F. <removed_email_address@domain.invalid> writes:

> I feel compelled to point out that it was Microsoft who started this
> whole mess, and they quickly figured out it was selecting the wrong
> people and they don't do it anymore. But the cat's out of the bag, and
> now every wannabe shop thinks that's the way to find smart
> people. It's not, it's the way to find people who are good at solving
> puzzles under pressure, and in the worst case to find people who are
> good at finding ridiculously clever (but unreadable/unmaintainable)
> answers to puzzles under pressure.

I think the usefulness of this interview technique depends on what
problem is used and what it is used for.  Namely, if the problem is
one that can be solved quickly, and while on autopilot, by pretty much
any decent programmer, and if it is being used simply as a straight
yes/no screen to block people who can't program their way out of a wet
paper bag, then I see "write code for this" as a useful interviewing
tool.  Maybe it isn't a problem where you are, but we've had people
claiming five years of programming experience who were unclear on how
two nested loops would execute.

For example, one question we frequently use is "write a function that
takes a two dimensional array and returns the sum of the minimum value
in each row".  Now, we understand that people are nervous in
interviews, and we'll occasionally give hints such as "this line here
throws a NullPointerException when you run it", or "that works, unless
the array contains a negative number", and give the candidate a chance
to revise their answer.  However, we have honestly had people
interview who couldn't write a doubly nested loop, or even explain
coherently how a sample solution worked.  Maybe it'd be easier if we
were interviewing for ruby programmers instead of java programmers.

I'll also point out that there's a quite prestigious shop located in
Mountain View, CA that handed me a whole bunch of "write code in
language X that does this" problems when I interviewed there. (and
they *still* didn't take me - http://xkcd.com/c192.html )

On penalizing ridiculous cleverness:

When my (now current) boss gave me that question above, she said
initially "in any language".  I scribbled something really short down,
and asked "you probably meant any imperative language, right?", after
which I gave a completely unimaginative imperative solution in
perl. (The language I was most familiar with at the time)

I don't go for the overly clever bizarre stuff at work - that's what
Ruby Q. is for.  Well, okay, I have been known to write bizarre perl
one-liners at the shell prompt, but not for anything that's going to
be run more than once.  I have however been known to occasionally use
techniques that some people might call obscure in production code if
the code overall becomes more elegant or easier to read.  I'd much
rather build a parser that can read the description of a data record
as provided by a vendor than have fifty lines of mostly cut-and-paste
but conceptually "simple" code that doesn't tell me at a glance
whether we're parsing the latest version of the format.

The point is, yes, maintainability is important, but I really don't
understand the animosity towards "cleverness" that seems to be showing
up here.  That sounds to me dangerously close to the same attitude
that keeps ruby and many other non-mainstream languages out of many
production environments on the grounds that "we'll never be able to
find anyone to maintain it".

Also, as a practical matter, I haven't seen this "cleverness" in any
of the subsequent interviews I've conducted from the other side of the
desk.  Frankly, I'd love some evidence that incoming candidates had
been exposed to something other than the industry standard languages
and platforms.  Exposure to functional programming and the thought
patterns that go with it is a *good* thing.  Being able to look at a
problem from multiple angles is a *good* thing.  Mental agility?
We're supposed to like that in a candidate.

Incidentally, my initial answer was:

(Plus @@(Min /@ #))&

Anyone care to identify the language?
Mike M. (Guest)
on 2007-06-01 21:54
(Received via mailing list)
On 6/1/07, Daniel M. <removed_email_address@domain.invalid> wrote:
>
> For example, one question we frequently use is "write a function that
> I'll also point out that there's a quite prestigious shop located in
> perl. (The language I was most familiar with at the time)
> whether we're parsing the latest version of the format.
> desk.  Frankly, I'd love some evidence that incoming candidates had
> Anyone care to identify the language?
>
> --
> s=%q(  Daniel M. -- removed_email_address@domain.invalid
>        puts "s=%q(#{s})",s.to_a.last       )
>        puts "s=%q(#{s})",s.to_a.last
>
>


I worked with a lead in a java shop that liked to ask this question:

"Write a function that reverses the *words* in a string" (in java)

Firstly, it would reveal if the candidate listens to the problem and
then goes about logically solving what was communicated to them (i.e.
its not reversing the string character by character).  If they get
crafty with the problem then kudos to them, but if they get stuck
she'll say that its ok to use java util classes to help solve the
problem.  Secondly if stuck since they claim to be java programmers
then they should know about the StringTokenizer combined with Stack
classes that makes this problem trivial to solve.

At first I thought this question was too simplistic (much like
FizzBuzz), but it really does fletch out the Heros from the Zeros.
Chris S. (Guest)
on 2007-06-01 22:05
(Received via mailing list)
On Jun 1, 11:53 am, "Mike M." <removed_email_address@domain.invalid> wrote:
> > > people. It's not, it's the way to find people who are good at solving
> > tool.  Maybe it isn't a problem where you are, but we've had people
> > interview who couldn't write a doubly nested loop, or even explain
> > When my (now current) boss gave me that question above, she said
> > the code overall becomes more elegant or easier to read.  I'd much
> > find anyone to maintain it".
> > Incidentally, my initial answer was:
> I worked with a lead in a java shop that liked to ask this question:
> classes that makes this problem trivial to solve.
>
> At first I thought this question was too simplistic (much like
> FizzBuzz), but it really does fletch out the Heros from the Zeros.

Isn't your test ambiguous? Do you want "Hello World" to become "World
Hello" or "olleH dlroW"? Or is that part of the test?
Mike M. (Guest)
on 2007-06-01 22:17
(Received via mailing list)
On 6/1/07, Chris S. <removed_email_address@domain.invalid> wrote:
> > > > now every wannabe shop thinks that's the way to find smart
> > > paper bag, then I see "write code for this" as a useful interviewing
> > > to revise their answer.  However, we have honestly had people
> >
> > > techniques that some people might call obscure in production code if
> > > production environments on the grounds that "we'll never be able to
> >
> >
> > then they should know about the StringTokenizer combined with Stack
> > classes that makes this problem trivial to solve.
> >
> > At first I thought this question was too simplistic (much like
> > FizzBuzz), but it really does fletch out the Heros from the Zeros.
>
> Isn't your test ambiguous? Do you want "Hello World" to become "World
> Hello" or "olleH dlroW"? Or is that part of the test?
>
>
>

Ah yes, thanks for jogging my memory, "Write a function that reverses
the words of a string"
Rob B. (Guest)
on 2007-06-01 22:56
(Received via mailing list)
On Jun 1, 2007, at 2:17 PM, Mike M. wrote:
>> > then goes about logically solving what was communicated to them
>>
>> Isn't your test ambiguous? Do you want "Hello World" to become "World
>> Hello" or "olleH dlroW"? Or is that part of the test?
>
> Ah yes, thanks for jogging my memory, "Write a function that reverses
> the words of a string"

I'd think that would be another opportunity to see how the person
works.  Do they notice the potential ambiguity of the requirement?
If not, how do they react when the other interpretation (from the one
they assumed) is pointed out?

Of course, giving one of the specifications:

assert_equal "World Hello", reverse_words("Hello World")
assert_equal "olleH dlroW", reverse_words("Hello World")

would clear the matter up (when asked).  (And it's been a couple
years since I've looked at JUnit so just imagine the equivalent Java
syntax ;-)

-Rob

Rob B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
Daniel M. (Guest)
on 2007-06-01 23:40
(Received via mailing list)
Hans F. <removed_email_address@domain.invalid> writes:

> Having not heard of this particular problem, I jumped to the
> conclusion that it was one of those "write this seemingly simple
> program but you're not cool unless you do it the clever way I'm
> thinking of" problems. If it's really used as just a "can you write a
> simple program" question, I'm all for that.

Right, which is why FizzBuzz or the minsum question I mentioned (or
even the "World Hello" problem) are fair game in an interview, but
"how do you detect a loop in a singly linked list in an efficient,
O(n) manner" is just not.  (Unless the candidate has just made the
claim that they've read all three of Knuth's books thoroughly and are
being an ass about it)

(Incidentally, I know of two different solutions to that problem,
neither of which are likely to ever be of any use to me at all.)
Rick D. (Guest)
on 2007-06-01 23:59
(Received via mailing list)
Like many others, I knocked this out in a few minutes, while I was
eating lunch.

I then decided, like others, to try to do it different ways.  I came
up with 6 different solutions in about an hour, ranging from quite
straightforward to bizarre and cryptic.

I hope that those who are familiar with my musings, ponderings and
pontifications will realize that the latter ones were out of my
wheelhouse.

ISTR that this problem came up not too long ago in the code golfing
community.  I won't go that far!

---
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/
Robert D. (Guest)
on 2007-06-02 00:01
(Received via mailing list)
On 6/1/07, Daniel M. <removed_email_address@domain.invalid> wrote:
<snip>
>
> Incidentally, my initial answer was:
>
> (Plus @@(Min /@ #))&
APL? A wild guess though.
>
> Anyone care to identify the language?
>
> --
> s=%q(  Daniel M. -- removed_email_address@domain.invalid
>        puts "s=%q(#{s})",s.to_a.last       )
>        puts "s=%q(#{s})",s.to_a.last
>
>
Robert
Sander L. (Guest)
on 2007-06-02 00:14
(Received via mailing list)
On 6/1/07, Daniel M. <removed_email_address@domain.invalid> wrote:
> .....
>
> Incidentally, my initial answer was:
>
> (Plus @@(Min /@ #))&
>
> Anyone care to identify the language?

Mathematica.
Ari B. (Guest)
on 2007-06-02 00:57
(Received via mailing list)
Hey all, I have a quick question on this quiz:
I have a working version of it, but I just want to compare and see
what everyone else got.

How many lines do you have it written in?

That's my big problem - making programs too long.

thanks,
~ Ari
English is like a pseudo-random number generator - there are a
bajillion rules to it, but nobody cares.
darren kirby (Guest)
on 2007-06-02 01:06
(Received via mailing list)
quoth the Ari B.:
> English is like a pseudo-random number generator - there are a
> bajillion rules to it, but nobody cares.

Mine is 8 lines (not including the shebang) two of which are 'end's. I
wrote
it in probably the most obvious way, so it's certainly not 'clever' or
anything.

-d
fREW (Guest)
on 2007-06-02 01:17
(Received via mailing list)
On 6/1/07, Robert D. <removed_email_address@domain.invalid> wrote:
> > --
> -- George Bernard Shaw
>
>

APL was my guest too.
Rick D. (Guest)
on 2007-06-02 01:59
(Received via mailing list)
On 6/1/07, darren kirby <removed_email_address@domain.invalid> wrote:
> > ~ Ari
> > English is like a pseudo-random number generator - there are a
> > bajillion rules to it, but nobody cares.
>
> Mine is 8 lines (not including the shebang) two of which are 'end's. I wrote
> it in probably the most obvious way, so it's certainly not 'clever' or
> anything.

As I said, I wrote 6 different versions, all of them are methods on
Integer, and a (1..100).each {|i| p i.fizz_buzzn)

where n is an integer.

The most obvious method has 8 lines inside the def/end, while the
shortest has one.
--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/
Bill K. (Guest)
on 2007-06-02 02:04
(Received via mailing list)
From: "Ari B." <removed_email_address@domain.invalid>
>
> Hey all, I have a quick question on this quiz:
> I have a working version of it, but I just want to compare and see
> what everyone else got.
>
> How many lines do you have it written in?

I typed it in as a one-liner in IRB just out of curiosity.  I figured
it was some kind of trick question, so I tried to be as non-clever as
possible.

After that I made a slightly shorter version of the one-liner just to
eliminate some duplication.  But still nothing very clever.  :)


Regards,

Bill
Daniel M. (Guest)
on 2007-06-02 05:46
(Received via mailing list)
"Sander L." <removed_email_address@domain.invalid> writes:

> On 6/1/07, Daniel M. <removed_email_address@domain.invalid> wrote:
>> .....
>>
>> Incidentally, my initial answer was:
>>
>> (Plus @@(Min /@ #))&
>>
>> Anyone care to identify the language?
>
> Mathematica.

Bingo.

And APL is significantly less legible than this. (Among other things,
I used ASCII there) Even J (APL's modern, ASCII-based descendant)
would be less legible than that.
Morton G. (Guest)
on 2007-06-02 07:38
(Received via mailing list)
On Jun 1, 2007, at 8:28 AM, Ruby Q. wrote:

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

I would not be surprised if this quiz produces the most submissions
of any quiz ever.

Regards, Morton
Robert D. (Guest)
on 2007-06-02 10:51
(Received via mailing list)
On 6/2/07, Daniel M. <removed_email_address@domain.invalid> wrote:
> >
> > Mathematica.
>
> Bingo.
Do you mean it is Mathematica or do you mean it is Bingo ;)

Oh well just realized I am a bad loser ;)
Robert
Daniel M. (Guest)
on 2007-06-02 16:07
(Received via mailing list)
Ruby Q. <removed_email_address@domain.invalid> writes:

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

Anyone care for a friendly game of golf?
I've got this in 67 characters...
unknown (Guest)
on 2007-06-02 16:43
(Received via mailing list)
Hi --

On Sat, 2 Jun 2007, Daniel M. wrote:

> Ruby Q. <removed_email_address@domain.invalid> writes:
>
>>   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".
>
> Anyone care for a friendly game of golf?
> I've got this in 67 characters...

I'm afraid I'm stuck on 71.  Is it OK to post solutions here at this
stage?


David
Brian C. (Guest)
on 2007-06-02 17:11
(Received via mailing list)
On Sat, Jun 02, 2007 at 09:42:13PM +0900, removed_email_address@domain.invalid 
wrote:
> >>  print "FizzBuzz".
> >
> >Anyone care for a friendly game of golf?
> >I've got this in 67 characters...
>
> I'm afraid I'm stuck on 71.  Is it OK to post solutions here at this
> stage?

67 here too, and nothing really clever in it.

$ wc fizzbuzz.rb
 0  4 67 fizzbuzz.rb
$ ruby fizzbuzz.rb | tail -5
Fizz
97
98
Fizz
Buzz
Brian C. (Guest)
on 2007-06-02 17:24
(Received via mailing list)
On Sat, Jun 02, 2007 at 09:06:50PM +0900, Daniel M. wrote:
> Ruby Q. <removed_email_address@domain.invalid> writes:
>
> >   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".
>
> Anyone care for a friendly game of golf?
> I've got this in 67 characters...

Actually, I've now got 65 character or 62 characters. The 62 character
version interprets the specification literally by printing "Fizz",
"Buzz" or
"FizzBuzz" *with* the double quotation marks :-)
Daniel M. (Guest)
on 2007-06-02 18:04
(Received via mailing list)
removed_email_address@domain.invalid writes:

> I'm afraid I'm stuck on 71.  Is it OK to post solutions here at this
> stage?

According to the rules posted, we need to wait 48 hours from the
initial posting, which will in my timezone (US Eastern) be at 8:28
tomorrow morning.

At this point, the only things fair to post (based on past quizzes)
would be:
- sample output
- unit tests
- speed measurements

You'd have to be careful, though, to construct a unit test that does
not itself contain a quiz solution.  I guess it's kosher to post this
test program, written in sh:

#! /bin/sh
RUBYSCRIPT=$1
if [ `ruby "$RUBYSCRIPT" | wc -l` -ne 100 ]; then
  echo "Fail linecount"; exit 1
fi
ruby "$RUBYSCRIPT" | \
  egrep -v '^([0-9]+|Fizz|Buzz|FizzBuzz)$' > /dev/null
if [ $? -eq 0 ]; then
  echo "Fail content"; exit 1
fi
# now a few spotchecks
spotcheck() {
  ruby "$RUBYSCRIPT" | nl | grep "^ *$1.$2\$" > /dev/null
  if [ $? -ne 0 ]; then
    echo "Fail $*"; exit 1
  fi
}
spotcheck 1 1
spotcheck 3 Fizz
spotcheck 5 Buzz
spotcheck 15 FizzBuzz
spotcheck 23 23
spotcheck 90 FizzBuzz
spotcheck 97 97
spotcheck 98 98
spotcheck 99 Fizz
spotcheck 100 Buzz

echo Passed
exit 0
Ari B. (Guest)
on 2007-06-02 18:27
(Received via mailing list)
Hey all,
my first ruby submission is coming up, and i'm pretty psyched - I'm
even cron-ing my email submission to try to be the first one in :-D

But I have a problem. In  my code, I want to use case - when
statements in it to reduce line wastage. BUT I get an error when I
try to use this sample code:

case s
when s + 1 == y and s - 1 == q

anyhelp?

also, modulus is x % y, right?

thanks,
---------------------------------------------------------------|
~Ari
"I don't suffer from insanity. I enjoy every minute of it" --1337est
man alive
Sharon P. (Guest)
on 2007-06-02 18:56
(Received via mailing list)
try &&
Ivo D. (Guest)
on 2007-06-02 18:57
(Received via mailing list)
My solution has 75 characters, damn, I will have another look at it!

to answer ari's questions:

> case s
> when s + 1 == y and s - 1 == q

try this:

case
when s+1==y && s-1==q

> also, modulus is x % y, right?

yes
James G. (Guest)
on 2007-06-02 19:09
(Received via mailing list)
On Jun 2, 2007, at 7:06 AM, Daniel M. wrote:

> Ruby Q. <removed_email_address@domain.invalid> writes:
>
>>   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".
>
> Anyone care for a friendly game of golf?
> I've got this in 67 characters...

Is that how you would solve it in your job interview?  Just curious.

James Edward G. II
Daniel M. (Guest)
on 2007-06-02 20:29
(Received via mailing list)
James Edward G. II <removed_email_address@domain.invalid> writes:

> On Jun 2, 2007, at 7:06 AM, Daniel M. wrote:
>> Anyone care for a friendly game of golf?
>> I've got this in 67 characters...
>
> Is that how you would solve it in your job interview?  Just curious.

Well, no.  In a job interview I'd give the first solution I came up
with, which is quite boring.  At least, initially.  If explicitly
asked for different solutions, maybe.  At a job interview I've alluded
to before, I was asked to write a perl one-liner that did a particular
task, and later as we had some extra time at the end of the interview,
(it was a marathon interview day, with interviews scheduled on the
hour) I spent a minute or two with the interviewer looking at ways to
play perlgolf with my solution.

Basically, trying to golf the solution is a form of joking around with
the interviewer,(*) and like anything of that nature, you do it only
when appropriate.

(*) albeit a highly geeky form of joke
William (Bill) Froelich (Guest)
on 2007-06-02 21:18
(Received via mailing list)
> > I've got this in 67 characters...
>
> Actually, I've now got 65 character or 62 characters. The 62
> character version interprets the specification literally by
> printing "Fizz", "Buzz" or "FizzBuzz" *with* the double
> quotation marks :-)

Speaking of literal interpetation, the original Quiz post came across in
my mail with a number of non-standard ASCII characters wrapped around
the Fizz and Buzz text.

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

I spent a bunch of time trying to figure out how to output those
(unsuccessfully) after getting my initial solution working.  Based on a
number of the other posts on the topic it appears that the real
requirement was to output Fizz, Buzz or FizzBuzz only without the other
characters. Is that correct?

Just curious while I wait to post my first quiz submission.

--Bill
Joshua B. (Guest)
on 2007-06-02 21:35
> Actually, I've now got 65 character or 62 characters. The 62 character
> version interprets the specification literally by printing "Fizz",
> "Buzz" or
> "FizzBuzz" *with* the double quotation marks :-)

I'll match your 62, but I'm still thinking that some clever tricks might
get it lower!

sh-3.2$ wc fizzbuzz.rb
       0       2      62 fizzbuzz.rb
sh-3.2$ ruby fizzbuzz.rb | tail -11
"FizzBuzz"
91
92
"Fizz"
94
"Buzz"
"Fizz"
97
98
"Fizz"
"Buzz"
I. P. (Guest)
on 2007-06-02 22:08
(Received via mailing list)
|William (Bill) Froelich|

WBF> I spent a bunch of time trying to figure out how to output
WBF> those (unsuccessfully) after getting my initial solution working.
WBF> Based on a number of the other posts on the topic it appears that
WBF> the real requirement was to output Fizz, Buzz or FizzBuzz only
WBF> without the other characters. Is that correct?
Yes. Probably this symbols came from non-standard quotation marks.
Sun P. (Guest)
on 2007-06-02 22:33
(Received via mailing list)
I golf too! :)
I got to reach 56 bytes, but I highly doubt I can shave one more byte
from
it.
Sammy L. (Guest)
on 2007-06-02 23:04
(Received via mailing list)
Sun P. wrote:
> I golf too! :)
> I got to reach 56 bytes, but I highly doubt I can shave one more byte
> from
> it.
>
I can't wait for tomorrow to see how you all got such ridiculously low
numbers =)
Todd B. (Guest)
on 2007-06-02 23:52
(Received via mailing list)
On 6/2/07, Sammy L. <removed_email_address@domain.invalid> wrote:
>
I'm down to 42 chars.


Just kidding :)  The best I could do was 74, and it looks crappy.

Todd
Robert D. (Guest)
on 2007-06-02 23:54
(Received via mailing list)
On 6/2/07, Sun P. <removed_email_address@domain.invalid> wrote:
> I golf too! :)
> I got to reach 56 bytes, but I highly doubt I can shave one more byte from
> it.
>
We failed, just look at the achieves, I do not consider that a spoiler
because I am sure James was aware of the Ruby ML community's attempt
to get it to 56 bytes in March if I recall correctly.

And no I guess nobody would golf at a job interview unless it were for
the PGA of course.

Robert
Patrick H. (Guest)
on 2007-06-03 00:01
(Received via mailing list)
I know at an interview I would start with (well not exactly, but this
makes checking golf results easier)...

pth

require "test/unit"

class TestFizzbuzz < Test::Unit::TestCase
  def test_output
    assert_equal(CORRECT,`ruby fizzbuzz.rb`)
  end
end

CORRECT = <<EOF
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
EOF
S.Volkov (Guest)
on 2007-06-03 00:02
(Received via mailing list)
"Daniel M." <removed_email_address@domain.invalid> wrote in message
news:removed_email_address@domain.invalid...
> Ruby Q. <removed_email_address@domain.invalid> writes:
>
>> 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".
>
> Anyone care for a friendly game of golf?
> I've got this in 67 characters...

56 chars
see 'Smallest FizzBuzz program' thread in comp.lang.ruby
Fred P. (Guest)
on 2007-06-03 00:05
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Yes, the task is to output the words "Fizz" and "Buzz" with no other
characters, it must be your email client playing up.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)

iD8DBQFGYc1V2vy7v+d+psQRAgbIAJ4pv+jdzhKjJUjVKAUkSHPWX0zoYQCfY+bn
YPrEzHRAHRtUBxYNLIkBhsA=
=rFW9
-----END PGP SIGNATURE-----
Brian C. (Guest)
on 2007-06-03 01:28
(Received via mailing list)
On Sun, Jun 03, 2007 at 02:35:02AM +0900, Joshua B. wrote:
> > Actually, I've now got 65 character or 62 characters. The 62 character
> > version interprets the specification literally by printing "Fizz",
> > "Buzz" or
> > "FizzBuzz" *with* the double quotation marks :-)
>
> I'll match your 62, but I'm still thinking that some clever tricks might
> get it lower!

I've got 60 now. But it sounds like the magic target is 56 :-(
Ari B. (Guest)
on 2007-06-03 06:14
(Received via mailing list)
On Jun 2, 2007, at 10:56 AM, Ivo D. wrote:

> when s+1==y && s-1==q
Alrighty - looks good so far. When would it be appropriate to use 'and'?

Also, i seem to be unable to put a range into an array. Yes, i
understand this is very simple, but when I did what I THOUGHT would
work, I can't get a range of numbers to be inserted into an array.
Apparently this does not work:
array = []
array = array << (1..100)

who knew! Not I,

help?
thanks,
---------------------------------------------------------------|
~Ari
Extra bonus fun question: If gsub! doesn't work for integers, what
could I use?
Todd B. (Guest)
on 2007-06-03 07:07
(Received via mailing list)
On 6/2/07, Ari B. <removed_email_address@domain.invalid> wrote:
>
> Apparently this does not work:
> array = []
> array = array << (1..100)
>
> who knew! Not I,
>
> help?
> thanks,
> ---------------------------------------------------------------|
What you create above is an array with an element that is a range, so:

irb(main):001:0> array = []
=> []
irb(main):002:1> array << (1..100) #you don't need 'array = ' in front
of this
=> [1..100]
irb(main):003:2> array
=> [1..100]
irb(main):004:0> array.class
=> Array
irb(main):005:0> array[0].class
=> Range
irb(main):006:0> array << "blah"
=> [1..100, "blah"]

I'm guessing you want an array created from a range?  If so, one way
would be:

irb(main):007:0> array = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Also, some range methods return an array (like (1..100).map {} for
example).
Sergey V. (Guest)
on 2007-06-03 07:30
(Received via mailing list)
----- Original Message -----
From: "Ari B." <removed_email_address@domain.invalid>
To: "ruby-talk ML" <removed_email_address@domain.invalid>
Sent: Saturday, June 02, 2007 10:12 PM
Subject: Re: [QUIZ] FizzBuzz (#126)
..

> Also, i seem to be unable to put a range into an array. Yes, i
> understand this is very simple, but when I did what I THOUGHT would
> work, I can't get a range of numbers to be inserted into an array.
> Apparently this does not work:
> array = []
> array = array << (1..100)

array = (1..100).to_a
# or
array = [*1..100]
# or (golfers favorite?)
array = *1..100
# or (if you need to add it to existing array):
array.push *1..100
Patrick H. (Guest)
on 2007-06-03 08:39
(Received via mailing list)
On 6/2/07, Sergey V. <removed_email_address@domain.invalid> wrote:
> > Apparently this does not work:
>
>
>

Don't forget these:

?d

is the same as 100 and save a character

puts :Fizz

will print Fizz, just as well as :Fizz and saves a character, and if
you really want to save a couple chars figure out how to only have the
Fizz and Buzz literals and combine them in the multiple of 15 space.

All that having been said, my solution (not golfed) will include
something like:

module Enumerable
  def map_every(n)
    m = n - 1
    result = []

    self.each_with_index do |elem,i|
      if i % n == m
        result << yield(elem,i)
      else
        result << elem
      end
    end

    result
  end
end
Robert D. (Guest)
on 2007-06-03 10:36
(Received via mailing list)
On 6/3/07, Sergey V. <removed_email_address@domain.invalid> wrote:
<snip>
> # or (golfers favorite?)
not quite
> array = *1..100
array=*1..?d
;)

Robert
Sun P. (Guest)
on 2007-06-03 15:08
(Received via mailing list)
A non-golf solution of mine :

for n in (1..100)
  if n%3==0 && n%5==0
    puts "FizzBuzz"
  elsif n%3==0
    puts "Fizz"
  elsif n%5==0
    puts "Buzz"
  else
    puts n
  end
end

Does above code fit for a job interview? :)
Robert D. (Guest)
on 2007-06-03 15:11
(Received via mailing list)
On 6/3/07, Sun P. <removed_email_address@domain.invalid> wrote:
>     puts n
>   end
> end
>
> Does above code fit for a job interview? :)
No idea, the recruiters are not here yet, they will arrive in an hour
and half ;)
R.
Stefan R. (Guest)
on 2007-06-03 15:20
S.Volkov wrote:
> 56 chars
> see 'Smallest FizzBuzz program' thread in comp.lang.ruby

Darn, just wanted to write that I got a 58 one here. We had that in
#ruby-lang once too and golfed about it a bit. IIRC we had a smaller one
than 58 (didn't store it back then), but I don't remember how small. If
somebody knows blinks e-mail...

Regards
Stefan
Enrique Comba R. (Guest)
on 2007-06-03 15:21
(Received via mailing list)
I didn't want to post mine as there was to much golfing around ;)

But ok...

Here would be my solution (I don't like it specially, but I hope
it'll do when the recruiters come ;) ):

1.upto(100) do |number|
   print "Fizz" if number % 3 == 0
   print "Buzz" if number % 5 == 0
   print number if number % 3 != 0 && number % 5 != 0
   puts ""
end

----
Enrique Comba R.
removed_email_address@domain.invalid

I always thought Smalltalk would beat Java, I just didn't know it
would be called 'Ruby' when it did.
-- Kent Beck
Sharon P. (Guest)
on 2007-06-03 16:15
(Received via mailing list)
Well, It's a few minutes early, but I've got an early morning tomorrow.

Here's three attempts from me.

First is my initial shot, which will cause many of you to cringe at
the use of nested ternary operators...
Second, I decided to mess with Fixnum.
Then I got a little bored and thought of something for our friends at
thedailywtf (still can't take to the new name)

I'm willing to go with whoever suggested this might bring in the
largest number of RubyQuiz responses yet.

Cheers,
Dave

#-------------------------------------------------
#Quick first attempt

1.upto(100) {|i| puts(i%15==0 ? 'FizzBuzz' : i%5==0 ? 'Buzz' : i%
3==0 ? 'Fizz' : i)}


#-------------------------------------------------
#Lets play with Fixnum

class Fixnum
   def fizz_buzzed
     a= (self%3==0 ? 'Fizz' : "")
     a+= 'Buzz' if self%5==0
     a= self.to_s if a==""
     a
   end
end

1.upto(100) {|i| puts i.fizz_buzzed}


#-------------------------------------------------
# How about something for thedailywtf.com?

def divisible_by_3(i)
   if i.to_s.size>1 then
     divisible_by_3(i.to_s.split(//).map{|char| char.to_i}.inject{|
a,b| a+b})
   else
     [3,6,9].include?(i)
   end
end

def divisible_by_5(i)
   ['0','5'].include?(i.to_s[-1].chr)
end

def divisible_by_15(i)
   divisible_by_3(i) && divisible_by_5(i)
end


1..100.each do |i|
    if divisible_by_15(i) then puts 'FizzBuzz'
    elsif divisible_by_3(i) then puts 'Fizz'
    elsif divisible_by_5(i) then puts 'Buzz'
    else puts i
    end
end
Robert D. (Guest)
on 2007-06-03 16:31
(Received via mailing list)
If I want the job ;)

X = [ %w{FizzBuzz} + %w{Fizz} * 4 ]
Y = %w{Buzz}
(1..100).each do |n|
  puts( X[n%3][n%5]) rescue puts( Y[n%5]||n )
end
Robert D. (Guest)
on 2007-06-03 16:34
(Received via mailing list)
and if I do not ;)

require 'zlib'
puts Zlib::GzipReader.new(DATA).read
__END__
?7`F☻♥ok.out ]Î;♫♥EÑÞ'↨cÀ|Ú¶ÙK▬?fVY↨9ƒ☻.%ÛHܳæ
9z¯ësCæx¼¿-ó´9ü¾Yÿµî÷b∟9¯ßLq,çQw◄
"ÄuNÑ¡øßÆ(q¸É↑↔n6I>
#Å&(IÚ¤Ù6:»ÙvÚ6:»Ø¶%M>6>¢£Ífi3t¬Ø♀%K>5>£ãÍæist¼Ø☻¥H[4[ 
‼Íö☺
ýØr²☺☻

--
You see things; and you say Why?
But I dream things that never were; and I say Why not?

-- George Bernard Shaw
Craig D. (Guest)
on 2007-06-03 16:40
(Received via mailing list)
Hi everyone,

Here's my solution. It's the first one that occurred to me, and it
only took a few mins. to write.

(1..100).each do |n|
   if (n % 3) == 0 && (n % 5) == 0
     puts "FizzBuzz"
   elsif (n % 3) == 0
     puts "Fizz"
   elsif (n % 5) == 0
     puts "Buzz"
   else
     puts n
   end
end

I tried it a few other ways just for fun. I'm happy with this one
that uses 'case.'

(1..100).each do |n|
   puts case
     when (n % 3 == 0) && (n % 5) == 0: "FizzBuzz"
     when n % 3 == 0: "Fizz"
     when n % 5 == 0: "Buzz"
     else n
   end
end


Regards,
Craig
Morton G. (Guest)
on 2007-06-03 16:42
(Received via mailing list)
Here are my solutions to Quiz 126.  Because it was the one that
popped into my mind when I read the quiz description, the first is
the one that I think I'd produce if challenged during a job interview.

<code>
# Simple, obvious (to me) way to do it.
(1..100).each do |n|
    case
    when n % 15 == 0 : puts 'FizzBuzz'
    when n % 5 == 0  : puts 'Buzz'
    when n % 3 == 0  : puts 'Fizz'
    else puts n
    end
end

# Not quite so obvious, but a little DRYer:
(1..100).each do |n|
    puts  case
          when n % 15 == 0 : 'FizzBuzz'
          when n % 5 == 0  : 'Buzz'
          when n % 3 == 0  : 'Fizz'
          else n
          end
end

# Of course, could do it with if-elsif-else ...
(1..100).each do |n|
    puts(
       if n % 15 == 0
          'FizzBuzz'
       elsif n % 5 == 0
          'Buzz'
       elsif n % 3 == 0
          'Fizz'
       else n
       end
    )
end

# ... or even with the ternary operator.
(1..100).each do |n|
    puts(
       n % 15 == 0 ? 'FizzBuzz' :
       n % 5 == 0  ? 'Buzz' :
       n % 3 == 0  ? 'Fizz' : n
    )
end
</code>

Regards, Morton
anansi (Guest)
on 2007-06-03 16:43
(Received via mailing list)
that's my clear and straight-forward solution, I would give on a job
interview:

#!/usr/bin/env ruby

$VERBOSE = true

1.upto(100) do |num|

   case  when num.modulo(3) == 0 && num.modulo(5) == 0      :puts
'fizzbuzz'

         when num.modulo(3) == 0                            :puts
'fizz'

         when num.modulo(5) == 0                            :puts
'buzz'

         else                                                puts
num
   end

end


--
greets

                     one must still have chaos in oneself to be able to
give birth to a dancing star
Todd B. (Guest)
on 2007-06-03 16:45
(Received via mailing list)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
>         numbers which are multiples of both three and five
>         print "FizzBuzz".
>
> Pretend you've just walked into a job interview and been hit with this question.
> Solve it as you would under such circumstances for this week's Ruby Q..

My "honest" solution (what I really would have submitted to the
interviewer):

arr = (1..100).map do |i|
  i = (("FizzBuzz" if i%15==0) or ("Fizz" if i%3==0) or ("Buzz" if
i%5==0) or i)
end
puts arr


I couldn't resist throwing in the Loki solution.  Why Loki?  Because
it's a mischievous rascal, and it makes excessive use of the name
"it", albeit misguidedly, which it thinks is fitting giving the recent
hoopla about "it":

require 'date'

class Fixnum
  @@shapes = {
    3 => "Fizz",
    5 => "Buzz"
  }

  def self.invoke it
    @@shapes = it if it.kind_of? Hash
  end

  def self.reveal
    puts @@shapes.value.join( ' ' )
  end

  def << it
    return self if it.empty?
    it
  end

  def options( sep="", it=[] )
    @@shapes.keys.sort.each do |k|
      it << @@shapes[k] if self%k == 0
    end
    self << it.join( sep )
  end
end

loki_roused = ARGV[0]

if loki_roused
  the_simpsons = {
    3=>"Homer",
    5=>"Marge",
    7=>"Bart",
    11=>"Lisa",
    13=>"Maggie"
  }
  Fixnum.invoke the_simpsons
end

(1..100).each do |i|
  puts i.options
end

if loki_disturbed
  jd = Date.today.jd
  puts "\n---------------------------------"
  puts "\n Out of the simpson family -- on this Julian day of #{jd},
Loki can shape shift into:\n   #{(it = jd.options "
").kind_of?(String) ? it : 'none of them'}"
  puts "---------------------------------\n"
end


Some thoughts:

This is, obviously, an incredibly easy programming puzzle -- as far as
writing down the pseudo code in english.  It took me, however, no lie,
a good half hour just to decide on a course of action.  In my head, I
struggled with the virtues of simplicity and the "coolness" of
conciseness, all while trying to avoid mediocrity.  Actual programming
was a breeze.  From there, though, no lie, at least fifteen minutes to
debug.  I'm not kidding.

Now, I'm the first to admit that I'm new to Ruby, and programming is
not my strong suit, but I would never think that I'm one of those
people that couldn't program themselves out of a paper bag.

Thinking about this quiz just reinforced what I already knew about
myself.  I'm not a guy who just jumps in and gets his hands dirty.  In
fact, I'm the exact opposite.  I over-think the problem and often get
nowhere.  If this were a test of performance under pressure, I'm
certain I would have failed to impress during the interview.

In any case, to the other newbies out there: don't be intimidated by
such frivolous pursuits of the lofty few such as "golf".  In fact, be
so bold as to join in if you dare.  But, as in all things, be
steadfast in your Ruby endeavors.  Enlightenment will come :)

Todd
Todd B. (Guest)
on 2007-06-03 17:01
(Received via mailing list)
On 6/3/07, Todd B. <removed_email_address@domain.invalid> wrote:
>
> (1..100).each do |i|
>   puts i.options
> end
>

Oops, this should be "if loki_roused"
Don L. (Guest)
on 2007-06-03 17:02
(Received via mailing list)
Hi All,

Attached is my first submission to the Ruby Q..  I am relatively
new to ruby (7 months) and I have never before been able to solve a
Ruby Q. without several days of head scratching effort. It is not
the most ruby centric code, but it only took me 10 minutes to complete.

Don L.
Brooklyn, New York


(1..100).each do |n|

   case
     when n.modulo(5) == 0 && n.modulo(3) == 0
     print 'FizzBuzz', ' '
     when n.modulo(5) == 0
     print 'Buzz', ' '
     when n.modulo(3) == 0
     print 'Fizz', ' '
     else
     print n, ' '
   end

end
I. P. (Guest)
on 2007-06-03 17:09
(Received via mailing list)
|Ruby Q.|

Everything is supposed to be a "FizzBuzz" unless having been declared
something other.

----
def fizzbuzz(value)
  result = "FizzBuzz"
  result.gsub!("Buzz", "") if value % 5 != 0
  result.gsub!("Fizz", "") if value % 3 != 0
  result = value if result.empty?
  result
end

(1..100).each {|x| puts fizzbuzz(x)}
----
Michael G. (Guest)
on 2007-06-03 17:18
(Received via mailing list)
My first Ruby Q. submission.

# Straightforward solution

(1..100).each do |n|
   print "Fizz" if 0 == n % 3
   print "Buzz" if 0 == n % 5
   print n if 0 != n % 3 and 0 != n % 5
   print "\n"
end

# Peter S. "extra fun" solution

class Fixnum
   alias old_to_s to_s

   def to_s
     value = ""
     value += "Fizz" if 0 == self % 3
     value += "Buzz" if 0 == self % 5
     value += self.old_to_s if "" == value
     value
   end
end

(0..100).each { |x| p x }

# make things right again
class Fixnum
   alias to_fizz_buzz to_s
   alias to_s old_to_s
end

# golf solution (67 chars)
1.upto(?d){|n|puts 0<n%3&&0<n%5?n:(1>n%3?"Fizz":'')+(1>n%5?"Buzz":'')}

Cheers,

Michael G.
grzm seespotcode net
Joshua B. (Guest)
on 2007-06-03 17:32
So, I've got to lay claim to the 56 byte solution:

sh-3.2$ wc fizzbuzz.rb
       0       2      56 fizzbuzz.rb
sh-3.2$ ruby fizzbuzz.rb | tail -11
"FizzBuzz"
91
92
"Fizz"
94
"Buzz"
"Fizz"
97
98
"Fizz"
"Buzz"

...but I'm not sure if I should post it. Would people consider that a
spoiler?
Robert D. (Guest)
on 2007-06-03 17:45
(Received via mailing list)
On 6/3/07, Joshua B. <removed_email_address@domain.invalid> wrote:
> "Buzz"
> "Fizz"
> 97
> 98
> "Fizz"
> "Buzz"
Have been there, but this is not a valid solution, sorry to say so :(
you gotta get rid of the quotes in the output.

>
> ...but I'm not sure if I should post it. Would people consider that a
> spoiler?
The non spoiler period is over already ;)

Cheers
Robert
William (Bill) Froelich (Guest)
on 2007-06-03 18:08
(Received via mailing list)
Here was my first attempt that was around 5 minutes of effort.  After
thinking about it more I ended up writing a second version (also below)
that was less creative.

--Bill

# First attempt

(1..100).each { |n|
  if n % 3 == 0 then
    print "Fizz"
  end
  if n % 5 == 0 then
    print "Buzz"
  end
  if (n%3 != 0) and (n%5 != 0) then
    print n
  end
  print "\n"
}


# Second Attempt

(1..100).each { |n|
  case
    when (n%3 == 0) && (n%5 == 0) then
      puts "FizzBuzz"
    when (n%3 == 0) then
      puts "Fizz"
    when (n%5 == 0) then
      puts "Buzz"
    else
      puts n
  end
}
Bill G. (Guest)
on 2007-06-03 18:29
(Received via mailing list)
It's been months, and everbody else is, so why not...

(1..100).each do |x|
  m3 = x.modulo(3) == 0
  m5 = x.modulo(5) == 0

  puts case
    when (m3 and m5) then 'FizzBuzz'
    when m3 then 'Fizz'
    when m5 then 'Buzz'
    else x
  end
end

I went for clarity and simplicity.
Joshua B. (Guest)
on 2007-06-03 18:40
Robert D. wrote:
> On 6/3/07, Joshua B. <removed_email_address@domain.invalid> wrote:
>> "Buzz"
>> "Fizz"
>> 97
>> 98
>> "Fizz"
>> "Buzz"
> Have been there, but this is not a valid solution, sorry to say so :(
> you gotta get rid of the quotes in the output.
Crud, I just tested at http://golf.shinh.org/p.rb?FizzBuzz and you're
right...

For those interested, the code was:

1.upto(?d){|i,x|i%5>0||x=:Buzz;p i%3>0?x||i:"Fizz#{x}"}
Sun P. (Guest)
on 2007-06-03 18:49
(Received via mailing list)
your code prints out quotes, which should be removed.

2007/6/3, Joshua B. <removed_email_address@domain.invalid>:
Fred P. (Guest)
on 2007-06-03 18:52
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

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

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)

iD8DBQFGYtTj2vy7v+d+psQRAqm7AJ4lq8Gmv4Q0teoEeG//H3LQppoA4QCbBNnp
8wWFeZolXrFhEbnH+WhqzjA=
=26q+
-----END PGP SIGNATURE-----
Sun P. (Guest)
on 2007-06-03 18:53
(Received via mailing list)
Sorry I didn't see previous posts.. ;)

2007/6/3, Joshua B. <removed_email_address@domain.invalid>:
Michael G. (Guest)
on 2007-06-03 18:54
(Received via mailing list)
On Jun 3, 2007, at 9:40 , Joshua B. wrote:

> Robert D. wrote:
>> Have been there, but this is not a valid solution, sorry to say so :(
>> you gotta get rid of the quotes in the output.
> Crud, I just tested at http://golf.shinh.org/p.rb?FizzBuzz and you're
> right...
>
> For those interested, the code was:
>
> 1.upto(?d){|i,x|i%5>0||x=:Buzz;p i%3>0?x||i:"Fizz#{x}"}

s/p/puts/ and you get the proper solution:

1.upto(?d){|i,x|i%5>0||x=:Buzz;puts i%3>0?x||i:"Fizz#{x}"}


Michael G.
grzm seespotcode net
Robert D. (Guest)
on 2007-06-03 18:57
(Received via mailing list)
On 6/3/07, Michael G. <removed_email_address@domain.invalid> wrote:
> >
> > 1.upto(?d){|i,x|i%5>0||x=:Buzz;p i%3>0?x||i:"Fizz#{x}"}
>
> s/p/puts/ and you get the proper solution:
if only 'puts'.length were 'p'.length ;)
Sun P. (Guest)
on 2007-06-03 19:03
(Received via mailing list)
Here is my 56B

1.upto(?d){|x|x%5>0||b=:Buzz;puts x%3>0?b||x:"Fizz%s"%b}

I think my code looks similar to Joshua's..

2007/6/3, Sun P. <removed_email_address@domain.invalid>:
Michael G. (Guest)
on 2007-06-03 19:04
(Received via mailing list)
On Jun 3, 2007, at 9:56 , Robert D. wrote:

>> > right...
>> >
>> > For those interested, the code was:
>> >
>> > 1.upto(?d){|i,x|i%5>0||x=:Buzz;p i%3>0?x||i:"Fizz#{x}"}
>>
>> s/p/puts/ and you get the proper solution:
> if only 'puts'.length were 'p'.length ;)

s/proper solution/expected results/

And 59 isn't bad, I should think :P

Michael G.
grzm seespotcode net
James G. (Guest)
on 2007-06-03 19:11
(Received via mailing list)
On Jun 3, 2007, at 6:07 AM, Sun P. wrote:

> A non-golf solution of mine :

Just as a reminder, please check that the no spoiler period has
expired before posting quiz solutions.  Thank you.

James Edward G. II
Patrick H. (Guest)
on 2007-06-03 19:12
(Received via mailing list)
My first thought:

(1..100).each do |i|
  case
  when i % 15 == 0
    puts "FizzBuzz"
  when i % 3 == 0
    puts "Fizz"
  when i % 5 == 0
    puts "Buzz"
  else
    puts i
  end
end

If I took 30 seconds to think about it on an interview, I would have a
unit test (see my earlier post) and something like this:

module Enumerable
  def map_every(n)
    m = n - 1
    result = []

    self.each_with_index do |elem,i|
      if i % n == m
        result << yield(elem,i)
      else
        result << elem
      end
    end

    result
  end
end

result = *1..100
result = result.map_every(3)  { "Fizz" }
result = result.map_every(5)  { "Buzz" }
result = result.map_every(15) { "FizzBuzz" }
puts result

----------------------------------------
 I peeked on the mailing list, so I won't participate in the golf
tournament -- and I am not particularly good at golfing in any case.

pth
Chris C. (Guest)
on 2007-06-03 19:17
(Received via mailing list)
On 6/1/07, Ruby Q. <removed_email_address@domain.invalid> wrote:
>
> question as a screener:
>
Here is my nice, ungolfed version.  But I took Peter's Extra Credit
challenge.

class Integer
  def inspect
    x = (self % 3 == 0 ? "Fizz" : "")
    x << ( self % 5 == 0 ? "Buzz" : "" )
    x.empty? ? self : x
  end
end

(1..100).each {|x| p x}

I did this live in front of a friend, then he tried it in java.  And
Obj-C.  I beat him in time and line count for both.  It was pretty
funny to watch him try.
Michael G. (Guest)
on 2007-06-03 19:25
(Received via mailing list)
On Jun 3, 2007, at 8:17 , Michael G. wrote:

> # golf solution (67 chars)
> 1.upto(?d){|n|puts 0<n%3&&0<n%5?n:(1>n%3?"Fizz":'')+(1>n%5?"Buzz":'')}

I can't count today: 70 chars.

Michael G.
grzm seespotcode net
Joshua B. (Guest)
on 2007-06-03 19:32
Michael G. wrote:
>
> s/proper solution/expected results/
>
> And 59 isn't bad, I should think :P
>
> Michael G.
> grzm seespotcode net

Thanks. I'd push it a bit further, but I think I've already wasted
enough time golfing. This has gotten me thinking though...

Mathematically speaking, finding the shortest/optimal solution to any
programming challenge is an NP problem. It might be fun to do a follow
up quiz where the goal is to write a code generator that can find the
elusive 56 byte golfing solution to the FizzBuzz quiz. If one were to
simply write a random ASCII string generator and test every possible 56
byte string, it would take less than 95^56 (or 5.656e110) iterations...

...or would that quiz be too hard?

;)

-Josh
Ken B. (Guest)
on 2007-06-03 19:41
(Received via mailing list)
On Fri, 01 Jun 2007 21:28:14 +0900, Ruby Q. wrote:

>
> Suggestion:  A [QUIZ] in the subject of emails about the problem helps
> everyone on Ruby T. follow the discussion.  Please reply to the
> original quiz message, if you can.
>
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=
>
> There has been some debate on the proper ways to screen programmers you
> intend to hire.  A common theory is that you really need to have the
> programmer write some code for you to accurately gauge their skill.
> Exactly what to have them write is another debate, but the blogosphere
> has recently been abuzz with this question as a screener:
>
>   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”.
>
> Pretend you've just walked into a job interview and been hit with this
> question. Solve it as you would under such circumstances for this week's
> Ruby Q..

class Integer
  def === num
    num % self == 0
  end
end

100.times do |x|
  case x
    when 15: puts "FizzBuzz"
    when 3: puts "Fizz"
    when 5: puts "Buzz"
    else puts x
  end
end
Hans F. (Guest)
on 2007-06-03 19:51
(Received via mailing list)
Daniel M. wrote:

> The point is, yes, maintainability is important, but I really don't
> understand the animosity towards "cleverness" that seems to be showing
> up here.  That sounds to me dangerously close to the same attitude
> that keeps ruby and many other non-mainstream languages out of many
> production environments on the grounds that "we'll never be able to
> find anyone to maintain it".
>

I suppose I should clarify what I mean by cleverness. I distinguish
between "clever" code and elegant code. Code that might be considered
clever but is in good taste I would term elegant. Golfing, fancy bit
manipulation by C programmers where the compiler would take care of it
anyway, etc. I term clever with a derogatory tone. The choice of terms
is almost entirely arbitrary. The point is that, as you said, in a job
interview what you want is a straightforward test of ability, not to
assess for on-the-spot puzzle solving ability.

> Also, as a practical matter, I haven't seen this "cleverness" in any
> of the subsequent interviews I've conducted from the other side of the
> desk.  Frankly, I'd love some evidence that incoming candidates had
> been exposed to something other than the industry standard languages
> and platforms.  Exposure to functional programming and the thought
> patterns that go with it is a *good* thing.  Being able to look at a
> problem from multiple angles is a *good* thing.  Mental agility?
> We're supposed to like that in a candidate.

Ya, that'd be elegant. :-)
Yossef M. (Guest)
on 2007-06-03 20:23
(Received via mailing list)
I have two solutions.  One is the quick job interview version:

(1..100).each { |x|  str = ''; str += 'Fizz' if (x % 3).zero?; str +=
'Buzz' if (x % 5).zero?; str = x if str.empty?; puts str }


The second is inspired by Peter S.'s early suggestion for "extra
fun".  It's not much different from the above, but it puts the logic
in Fixnum:

class Fixnum
  def to_s
    str = ''
    str += 'Fizz' if (self % 3).zero?
    str += 'Buzz' if (self % 5).zero?
    str = '%d' % self if str.empty?
    str
  end
end

(1..100).each { |x|  puts x }


My favorite thing about that solution is seeing irb prompts like
"irb(main):013:FizzBuzz>" and seeing that the range is output as
"1..Buzz"
Brian C. (Guest)
on 2007-06-03 20:25
(Received via mailing list)
My solution: 63 characters without the quotes, or 60 characters with
them.

1.upto(100){|i|i%3==0&&x="Fizz";i%5==0&&x="#{x}Buzz";puts x||i}

1.upto(100){|i|i%3==0&&x="Fizz";i%5==0&&x="#{x}Buzz";p x||i}
Ryan L. (Guest)
on 2007-06-03 20:26
(Received via mailing list)
My first, obvious solution:

(1..100).each do |i|
  if (i % 3 == 0) and (i % 5 == 0)
    puts "FizzBuzz"
  elsif (i % 3 == 0)
    puts "Fizz"
  elsif (i % 5 == 0)
    puts "Buzz"
  else
    puts i
  end
end

Trying to reduce the redundant ifs:

(1..100).each do |i|
  s = ''
  s << "Fizz" if (i % 3 == 0)
  s << "Buzz" if (i % 5 == 0)
  puts(s == '' ? i : s)
end

The above seems unique among the solutions I've read so far.

Ryan
Brian C. (Guest)
on 2007-06-03 20:27
(Received via mailing list)
On Sun, Jun 03, 2007 at 11:40:51PM +0900, Joshua B. wrote:
> Crud, I just tested at http://golf.shinh.org/p.rb?FizzBuzz and you're
> right...
>
> For those interested, the code was:
>
> 1.upto(?d){|i,x|i%5>0||x=:Buzz;p i%3>0?x||i:"Fizz#{x}"}
               ^^
Why the ,x here? x is locally scoped within the block anyway, and it
works
without it.
James G. (Guest)
on 2007-06-03 20:29
(Received via mailing list)
This solution cracked me up, but there is a typo in it...

On Jun 3, 2007, at 9:49 AM, Fred P. wrote:

> puts '59'
> puts 'FizzBuzz
> puts '61'

The middle line there is missing a quote.  ;)

James Edward G. II
paddor (Guest)
on 2007-06-03 20:32
(Received via mailing list)
my first solution:
(1..100).each do |n|
  print :Fizz if (n % 3) == 0
  print :Buzz if (n % 5) == 0
  print n if (n % 3) != 0 and (n % 5) != 0
  print "\n"
end

and my second one:
(1..100).each { |n| puts n % 3 == 0 ? n % 5 == 0 ? :FizzBuzz : :Fizz :
n % 5 == 0 ? :Buzz : n }

greets, paddor


2007/6/1, Ruby Q. <removed_email_address@domain.invalid>:
Gregory B. (Guest)
on 2007-06-03 20:39
(Received via mailing list)
On 6/1/07, Ruby Q. <removed_email_address@domain.invalid> wrote:

> Pretend you've just walked into a job interview and been hit with this question.
> Solve it as you would under such circumstances for this week's Ruby Q..

I'd probably want to do something a little clever but not anything
*too* unorthodox, so here's my solution:

def replace(n,list=[["FizzBuzz",15],["Buzz",5],["Fizz",3]])
  list.each { |r,m| return r if n % m == 0 }
  return n
end

puts (1..100).map { |e| replace(e) }
Bill G. (Guest)
on 2007-06-03 20:43
(Received via mailing list)
On 6/3/07, James Edward G. II <removed_email_address@domain.invalid> wrote:
> This solution cracked me up, but there is a typo in it...
>
> On Jun 3, 2007, at 9:49 AM, Fred P. wrote:
>
> > puts '59'
> > puts 'FizzBuzz
> > puts '61'
>
> The middle line there is missing a quote.  ;)

But would you hire him (minus the typo)?  I'd be a bit worried that
he'd shown up for a job interview with a hangover ;)
Sammy L. (Guest)
on 2007-06-03 20:44
(Received via mailing list)
Awesome!
darren kirby (Guest)
on 2007-06-03 20:46
(Received via mailing list)
So: much like Marcel Proust biting into a madelaine, when I read this
quiz on
Friday I had a rush of old memories. I have never heard of fizzbuzz
being
used as a recruitment technique before, however, I am familiar with it
because back in high school we played it as a drinking game. If we were
feeling particularly hardcore we would also add in 'Bang' for multiples
of 7.
I had as much as forgotten about fizzbuzz as I haven't though about it
in
over twelve years or so...

Anyway, I have deviated from the official spec in a few ways here. First
of
all, I saw no reason to stop at 100, so my solution will print results
for
any user-specified 'n'. Rather than golfing, which I am no good at, I
decided
to go with an obvious solution.

The second deviation is that because the solution is fairly short (ie:
about a
paragraph) I thought it would be interesting to write solutions in a few
other languages as a point of comparison. To that end I also wrote
solutions
in Python, Lua, Scheme, and plain old C. Hopefully you can forgive me
some
off-topicness for posting these as well.

On with the code:

# fizz.rb
1.upto(ARGV[0].to_i) do |n|
  if n % 15 == 0
    print "FizzBuzz "
  elsif n % 5 == 0
    print "Buzz "
  elsif n % 3 == 0
    print "Fizz "
  else print "#{n} "
  end
end
puts

# fizz.py
import sys
for n in range(1,int(sys.argv[1])+1):
    if n % 15 == 0:
        sys.stdout.write("FizzBuzz ")
    elif n % 3 == 0:
        sys.stdout.write("Fizz ")
    elif n % 5 == 0:
        sys.stdout.write("Buzz ")
    else: sys.stdout.write("%i " % n)
print

-- fizz.lua
for n=1,arg[1] do
  if n % 15 == 0 then
    io.write("FizzBuzz ")
  elseif n % 3 == 0 then
    io.write("Fizz ")
  elseif n % 5 == 0 then
    io.write("Buzz ")
  else
    io.write(n .. " ")
  end
end
print()

/* fizz.c */
#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;
    for (i = 1; i <= atoi(argv[1]); i++) {
        if (i % 15 == 0)
            printf("%s ", "FizzBuzz");
        else if (i % 3 == 0)
            printf("%s ", "Fizz");
        else if (i % 5 == 0)
            printf("%s ", "Buzz");
        else
            printf("%i ", i);
    }
    printf("\n");
    return 0;
}

;;; fizz.scm
(define (fizz x)
  (define (mod5? n)
    (if (eq? (modulo n 5) 0) #t #f))
  (define (mod3? n)
    (if (eq? (modulo n 3) 0) #t #f))
  (define (fizz-iter n x)
     (cond
       ((> n x) (newline) #t)
       ((and (mod3? n) (not (mod5? n))) (display "Fizz ")
          (fizz-iter (+ n 1) x))
       ((and (mod5? n) (not (mod3? n))) (display "Buzz ")
          (fizz-iter (+ n 1) x))
       ((and (mod5? n) (mod3? n)) (display "FizzBuzz ")
          (fizz-iter (+ n 1) x))
       (else (display n) (display " ")
          (fizz-iter (+ n 1) x))))
  (fizz-iter 1 x))

cheers,
-d
Daniel M. (Guest)
on 2007-06-03 20:48
(Received via mailing list)
Ruby Q. <removed_email_address@domain.invalid> writes:

> Pretend you've just walked into a job interview and been hit with
> this question.  Solve it as you would under such circumstances for
> this week's Ruby Q..

# Well, Mr. Martin, this is just a simple little question we ask all of
# our programming candidates.  Let's see what you do with "FizzBuzz":

(1..100).each{|i|
  x = ''
  x += 'Fizz' if i%3==0
  x += 'Buzz' if i%5==0
  puts(x.empty? ? i : x);
}

# Okay, very straightforward.  You know, I've never been an overly big
# fan of the question mark-colon operator.  It always seemed to me one
# of the constructs in C most open to abuse.
#
# What's that?  Oh, okay, so how would you eliminate that ?: in favor
# of something more Rubyish?

(1..100).each{|i|
  x = i
  x = 'Fizz' if i%3==0
  x += 'Buzz' if i%5==0 rescue x='Buzz'
  puts x;
}

# Well using "rescue" certainly does feel more Rubyish.
#
# It says here that you've done significant work with functional
# languages.  Could you rewrite this to take advantage of higher order
# functions?

a = [proc{|x|x}, proc{|x|x}, proc{:Fizz}] * 5
a[4]=a[9]=proc{:Buzz}
a[14]=proc{:FizzBuzz}
(1..100).zip(a*9){|i,l|puts l[i]}

# Well that's rather cryptic, and I don't necessarily like the manual
# computation behind the indexes 4, 9, and 14.  I'd prefer something
# that, like your first two solutions, combined the Fizz and Buzz so
# that the FIzzBuzz printed every fifteen spots is a natural
# consequence.

f = proc{'Fizz'}
b = proc{|x|x+'Buzz' rescue :Buzz}
i = proc{|x|x}
(1..100).zip([i,i,f]*99,[i,i,i,i,b]*99){|n,p,q|puts q[p[n]]}

# Uh... yes.  In that I can see the two cycles, the 3-cycle and the
# 5-cycle, but I'm not sure that turned out as clear as I had hoped.
#
# I wonder if a hybrid approach where you used anonymous functions
# only for one of the two words is worth considering...

b=proc{|i,s|i%5==0?s+'Buzz':s rescue :Buzz}
puts (1..100).map{|i|b[i,i%3==0?'Fizz':i]}

# There's that ?: operator again.
#
# You know, you aren't really using arbitrary functions there.  I wonder
# if lambda functions aren't overkill for this problem.  What if you
# repeated the pattern where you showed the two cycles, but used simple
# strings instead?

$;='/'
(1..100).zip('//Fizz'.split*99,'////Buzz'.split*99) {|a|
puts(('%d%s%s'%a).sub(/\d+(?=\D)/,''))}

# Well, okay, you've shown that sometimes strings are not as easy to
read
# as one might think.
#
# I noticed you using a regular expression there and I note that your
# resume shows extensive experience with regular expressions.  That's a
# rather small example on which to judge your regular expression
# experience.  Could you somehow make more use of regular expressions?

(1..100).map{|i|"#{i}\n"}.join.
  gsub(/^([369]?[0369]|[147][258]|[258][147])$/m,'Fizz\1').
  gsub(/\d*[50]$/m,'Buzz').gsub(/z\d+/,'z').display

# Let us never speak of this again.
#
# Well, Mr. Martin, I think you've shown technically what we're looking
# for.  Tell me, do you golf?

puts (1..100).map{|a|x=a%3==0?'Fizz':'';x+='Buzz'if a%5==0;x.empty??
a:x}

# Uh, that

puts (1..100).map{|i|[i,:Buzz,:Fizz,:FizzBuzz][i%5==0?1:0+i%3==0?2:0]}

# Mr. Martin, that's not

puts (1..100).map{|i|i%15==0?:FizzBuzz:i%5==0?:Buzz:i%3==0?:Fizz:i}

# I, uh, hadn't meant that kind of golf.
# (Though, as an aside, you could save characters by using 1.upto(100)
#  and by using <1 in place of ==0)
#
# However, these last few examples bring home a point I was worrying
about
# before that we haven't really touched on yet - all of these have
# varying degrees of readability, yet Ruby is supposed to be an
eminently
# readable language.  How could you make this code more readable?

puts (1..100).map{|i|
  case i%15
  when 0        then :FizzBuzz
  when 5,10     then :Buzz
  when 3,6,9,12 then :Fizz
  else i
  end
}

# Well, that certainly is an improvement, though separating the "puts"
# from the rest of the logic might be slightly confusing and I'd prefer
# a more direct translation from the English program specification to
# the code.

(1..100).each {|i|
  if    i%5==0 and i%3==0 then puts :FizzBuzz
  elsif i%5==0            then puts :Buzz
  elsif            i%3==0 then puts :Fizz
  else                         puts i
  end
}

# Well now.
#
# Okay, are there any other tricks you have to show before we wrap this
# up?

h=Hash.new{|d,k|k>14?h[k%15]:nil}
h[0]=:FizzBuzz
h[3]=h[6]=h[9]=h[12]=:Fizz
h[5]=h[10]=:Buzz
puts (1..100).map{|i|h[i]||i}

# That looks rather familiar and similar to your first anonymous
function
# solution.  I think we've both had enough of this problem by now.
#
# Well, it's been nice talking to you, Mr. Martin, and I thank you for
# your interest in CompuGlobalMegaTech.  We'll be in touch over the next
# few days with our decision.
James G. (Guest)
on 2007-06-03 21:02
(Received via mailing list)
On Jun 3, 2007, at 11:47 AM, Daniel M. wrote:

> # Well, it's been nice talking to you, Mr. Martin, and I thank you for
> # your interest in CompuGlobalMegaTech.  We'll be in touch over the
> next
> # few days with our decision.

They would be a fool not to hire you.  ;)

James Edward G. II
Robert D. (Guest)
on 2007-06-03 21:04
(Received via mailing list)
This is for a higher position than sheer Software Engineer, pah...

puts( %w{ Fizz Buzz FizzBuzz } * 33 + [*1..100].reject{|n|
(n%3*n%5).zero?  }.sort_by{ |n| exercise_is_left_to_the_reader n
}[0..99].join("\n") )
James G. (Guest)
on 2007-06-03 21:05
(Received via mailing list)
On Jun 1, 2007, at 7:28 AM, Ruby Q. wrote:

> Pretend you've just walked into a job interview and been hit with
> this question.  Solve it as you would under such circumstances for
> this week's Ruby Q..

This is my solution from the time when I was considering this as a quiz.

#!/usr/bin/env ruby -w

1.upto(100) do |i|
   if i % 5 == 0 and i % 3 == 0
     puts "FizzBuzz"
   elsif i % 5 == 0
     puts "Buzz"
   elsif i % 3 == 0
     puts "Fizz"
   else
     puts i
   end
end

__END__

James Edward G. II
Benjamin A. (Guest)
on 2007-06-03 21:13
(Received via mailing list)
I laughed at how silly the quiz is, and then I did my solution without
fully reading the spec. :(

(1..100).each do |i|
  print i.to_s + ' '
  print 'Fizz' if i % 3 == 0
  print 'Buzz' if i % 5 == 0
  puts
end

I missed the 'instead of the number' part.

Ben
Rick D. (Guest)
on 2007-06-03 21:16
(Received via mailing list)
On 6/3/07, James Edward G. II <removed_email_address@domain.invalid> wrote:
> This solution cracked me up, but there is a typo in it...
>
> On Jun 3, 2007, at 9:49 AM, Fred P. wrote:
>
> > puts '59'
> > puts 'FizzBuzz
> > puts '61'
>
> The middle line there is missing a quote.  ;)

The 'safer' way to do this approach might be something like:

%w{1   2  Fizz  4 Buzz Fizz  7  8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
             16  17  Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29
FizzBuzz
       31  32  Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz
       46  47  Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz
       61  62  Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz
       76  77  Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz
       91  92  Fizz 94 Buzz Fizz 97 98 Fizz Buzz
       }.each {|x| puts x}

Oops now I have 11 solutions! <G>



--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

IPMS/USA Region 12 Coordinator
http://ipmsr12.denhaven2.com/

Visit the Project Mercury Wiki Site
http://www.mercuryspacecraft.com/
darren kirby (Guest)
on 2007-06-03 21:18
(Received via mailing list)
quoth the Daniel M.:
> Ruby Q. <removed_email_address@domain.invalid> writes:
> > Pretend you've just walked into a job interview and been hit with
> > this question.  Solve it as you would under such circumstances for
> > this week's Ruby Q..
>
> # Well, Mr. Martin, this is just a simple little question we ask all of
> # our programming candidates.  Let's see what you do with "FizzBuzz":

<snip humourous, insightful, and bizarre solutions>

That was fantastic. Seriously, it made my morning!

-d
unknown (Guest)
on 2007-06-03 21:20
(Received via mailing list)
Hi --

On Mon, 4 Jun 2007, Rick DeNatale wrote:

>
> The 'safer' way to do this approach might be something like:
>
> %w{1   2  Fizz  4 Buzz Fizz  7  8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
>            16  17  Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz
>        31  32  Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz
>        46  47  Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz
>        61  62  Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz
>        76  77  Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz
>        91  92  Fizz 94 Buzz Fizz 97 98 Fizz Buzz
>        }.each {|x| puts x}

Or:

   puts %w{ 1 2 Fizz 4 ... }

:-)


David
Drew O. (Guest)
on 2007-06-03 21:25
One-liner?

(1..100).each{|i|puts
i%3==0?(i%5==0?"FizzBuzz":"Fizz"):(i%5==0?"Buzz":i)}
S.Volkov (Guest)
on 2007-06-03 22:01
(Received via mailing list)
#!/bin/env ruby

=begin
"Ruby Q." <removed_email_address@domain.invalid> wrote in message
news:removed_email_address@domain.invalid...
..
> 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".
>
> Pretend you've just walked into a job interview and been hit with this
> question.
> Solve it as you would under such circumstances for this week's Ruby Q..

The task itself is quite boring, so I decided to imagine how
different programmers may try to pass the interview.
I hope we'll see what the recruiter may think.

Oh! And I played golf, just for fun, hope you will enjoy it too.
=end

##
# Q126 solution
# by Sergey V.
##

##
# job interview style
##
# Java programmer
def sol1 maxn=100
    for i in 1..maxn
        if i%3 == 0 && i%5 == 0
            puts "FizzBuzz"
        elsif i%3 == 0
            puts "Fizz"
        elsif i%5 == 0
            puts "Buzz"
        else
            puts i
        end
    end
end
puts '### TC1'
sol1 15

##
# Same as above,
# but the code is more manageable
def sol1a maxn=100
    for i in 1..maxn
        if i%3 == 0 && i%5 == 0
            s = "FizzBuzz"
        elsif i%3 == 0
            s = "Fizz"
        elsif i%5 == 0
            s = "Buzz"
        else
            s = i.to_s
        end
        puts s
    end
end
puts '### TC1a'
sol1a 15

##
# Lisp programmer
def sol2 maxn=100
    puts( (1..maxn).map{ |i|
        i2s=lambda{ |n,s|
            if (i%n).zero? : s else '' end
        }
        lambda{ |s|
            if s.empty? : i else s end
        }.call i2s[3,'Fizz'] + i2s[5,'Buzz']
    } )
end
puts '### TC2'
sol2 15

##
# 1 year of Ruby experience
def sol3 maxn=100
    1.upto(maxn){ |n|
        s = "Fizz" if (n%3).zero?
        (s||='') << "Buzz" if (n%5).zero?
        puts s||n
    }
end
puts '### TC3'
sol3 15

##
# Trying to get extra points for reusability..
class Fixnum
    def toFizzBuzz
        s = 'Fizz' if modulo(3).zero?
        s = "#{s}Buzz" if modulo(5).zero?
        s || to_s
    end
end
def sol4 maxn
    1.upto(maxn){ |n| puts n.toFizzBuzz }
end
puts '### TC4'
sol4 15

##
# Extra points for expandability
#.. who knows what else recruiters are looking for?

__END__

##
# Golf style
1.upto(?d){|i|puts ["#{x=[:Fizz][i%3]}Buzz"][i%5]||x||i}# 56
1.upto(?d){|i|x=[:Fizz][i%3];puts i%5<1?"#{x}Buzz":x||i}# 56
1.upto(?d){|i|i%3<1&&x=:Fizz;puts i%5<1?"#{x}Buzz":x||i}# 56
Ari B. (Guest)
on 2007-06-03 22:10
(Received via mailing list)
Arlighty! my first submission. If I ever get asked this at a job
interview for, say, the local bookstore  (i'm not exactly old enough
to get what most people call a 'real' job), I'll be ready:

1.upto(?d) do |x|
   p 'fizzBuzz'  if x % 3  == 0 && x % 5
   p 'fizz'  if x % 3 == 0
   p 'buzz'  if x % 5 == 0
   p x if x % 3 != 0
end


for those who wrote it in 58 chars..... I don't know what to say...
-------------------------------------------------------|
~ Ari
crap my sig won't fit
S.Volkov (Guest)
on 2007-06-03 22:12
(Received via mailing list)
"Robert D." <removed_email_address@domain.invalid> wrote in message
news:removed_email_address@domain.invalid...
> If I want the job ;)
>
> X = [ %w{FizzBuzz} + %w{Fizz} * 4 ]
> Y = %w{Buzz}
> (1..100).each do |n|
>  puts( X[n%3][n%5]) rescue puts( Y[n%5]||n )
> end
Robert, you are not kind to guys who will maintain your code.
Do you want the job or demonstration of your smartness?
It's could be great for small startup doing R&D,
but not for enterprise-like development.
imho: in any situation: KISS!
Robert D. (Guest)
on 2007-06-03 22:13
(Received via mailing list)
On 6/3/07, removed_email_address@domain.invalid 
<removed_email_address@domain.invalid> wrote:
> >> > puts 'FizzBuzz
> >            61  62  Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz
> >            76  77  Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz
> >            91  92  Fizz 94 Buzz Fizz 97 98 Fizz Buzz
> >            }.each {|x| puts x}
>
> Or:
>
>    puts %w{ 1 2 Fizz 4 ... }
.join("\n")
>
> :-)
:-))
>
>
> David
>
Robert
Ari B. (Guest)
on 2007-06-03 22:14
(Received via mailing list)
Ok, minor change to my prog - at least it will cut away 10 chars though.

1.upto(?d) do |x|
   p 'fizzBuzz'  if x % 15  == 0
   p 'fizz'  if x % 3 == 0
   p 'buzz'  if x % 5 == 0
   p x if x % 3 != 0
end


--------------------------------------------|
If you're not living on the edge,
then you're just wasting space.
Joshua B. (Guest)
on 2007-06-03 22:25
Brian C. wrote:
> On Sun, Jun 03, 2007 at 11:40:51PM +0900, Joshua B. wrote:
>> Crud, I just tested at http://golf.shinh.org/p.rb?FizzBuzz and you're
>> right...
>>
>> For those interested, the code was:
>>
>> 1.upto(?d){|i,x|i%5>0||x=:Buzz;p i%3>0?x||i:"Fizz#{x}"}
>                ^^
> Why the ,x here? x is locally scoped within the block anyway, and it
> works
> without it.

Yeah, I realized that shortly after posting this...still, I'm over by
2...

Oh, and just to clarify my earlier suggestion of a 56 chr random code
generator...my rough guestimate is that it would take all the computers
on the earth working together about 10^80 times the age of the universe
to find the solution...

...you know, just so all you golfers don't feel so bad.

-Josh
James G. (Guest)
on 2007-06-03 22:25
(Received via mailing list)
On Jun 3, 2007, at 1:11 PM, Robert D. wrote:

> On 6/3/07, removed_email_address@domain.invalid <removed_email_address@domain.invalid> 
wrote:
>>    puts %w{ 1 2 Fizz 4 ... }
> .join("\n")

I think you were kidding, but just to be clear, the join() call is
not needed here.

James Edward G. II
Robert D. (Guest)
on 2007-06-03 22:27
(Received via mailing list)
On 6/3/07, S.Volkov <removed_email_address@domain.invalid> wrote:
> "Robert D." <removed_email_address@domain.invalid> wrote in message
> news:removed_email_address@domain.invalid...
> > If I want the job ;)
> >
> > X = [ %w{FizzBuzz} + %w{Fizz} * 4 ]
> > Y = %w{Buzz}
> > (1..100).each do |n|
> >  puts( X[n%3][n%5]) rescue puts( Y[n%5]||n )
> > end
> Robert, you are not kind to guys who will maintain your code.
That could be discussed, but this is a small entity, from my
experience maintenance nightmares come from bad design and code
dependencies. There would be some nice unit tests and if the
maintainer cannot figure out this code she can rewrite it.

> Do you want the job or demonstration of your smartness?
Would I like a job that does not fit my style - unless unemployed.

This is not very smart a solution, it reflects some features of Ruby,
after all they are hiring a Ruby developer not a C or Perl developer.
> It's could be great for small startup doing R&D,
> but not for enterprise-like development.
> imho: in any situation: KISS!

This is strong an expression, I will not take offense, others might.

Cheers
Robert
Pieter V. (Guest)
on 2007-06-03 22:34
(Received via mailing list)
Two quiz solutions here - one as per my interview situation, and one
for golfing.
Todd B. (Guest)
on 2007-06-03 22:37
(Received via mailing list)
On 6/3/07, Joshua B. <removed_email_address@domain.invalid> wrote:
>
> Oh, and just to clarify my earlier suggestion of a 56 chr random code
> generator...my rough guestimate is that it would take all the computers
> on the earth working together about 10^80 times the age of the universe
> to find the solution...

Just build a self-sustaining computer complete with time-travel
capabilities, programmed to reboot a few eons every once and a while,
and, poof there you go ... an instant solution to any NP problem!  I
wonder if Turing thought of such things.
unknown (Guest)
on 2007-06-03 22:42
(Received via mailing list)
In message
<removed_email_address@domain.invalid>, "Todd
Benson" writes:
>Just build a self-sustaining computer complete with time-travel
>capabilities, programmed to reboot a few eons every once and a while,
>and, poof there you go ... an instant solution to any NP problem!  I
>wonder if Turing thought of such things.

Asimov did.  :)

-s
Robert D. (Guest)
on 2007-06-03 23:26
(Received via mailing list)
On 6/3/07, James Edward G. II <removed_email_address@domain.invalid> wrote:
> On Jun 3, 2007, at 1:11 PM, Robert D. wrote:
>
> > On 6/3/07, removed_email_address@domain.invalid <removed_email_address@domain.invalid> 
wrote:
> >>    puts %w{ 1 2 Fizz 4 ... }
> > .join("\n")
>
> I think you were kidding, but just to be clear, the join() call is
> not needed here.
No I was not, I was just wrong :)
Robert
S.Volkov (Guest)
on 2007-06-04 00:11
(Received via mailing list)
"Robert D." <removed_email_address@domain.invalid> wrote in message
..
>> Robert, you are not kind to guys who will maintain your code.
> That could be discussed, but this is a small entity, from my
> experience maintenance nightmares come from bad design and code
> dependencies.
Sure, you are right.
But please don't forget, that 'small entity' can cause 'big problem' if
muliplyed by huge number.
Given 100 average-level programmers, how many will be able to expand
your
solution
to handle addition of one more multiplyer, say 7-Gozz?
Enterprise managers face luck of experienced programmers to execute
routine
maintenance tasks,
so simple solution for simple task is a _must_.

>> Do you want the job or demonstration of your smartness?
> This is not very smart a solution, it reflects some features of Ruby,
> after all they are hiring a Ruby developer not a C or Perl developer.
I didn't say it was smart solution :)

>> imho: in any situation: KISS!
> This is strong an expression, I will not take offense, others might.
I'm terrybly sorry, no offense was intended (I forgot to mention this
specifically in first place)!
ashamed,
Sergey V.
Rick D. (Guest)
on 2007-06-04 00:15
(Received via mailing list)
On 6/3/07, Joshua B. <removed_email_address@domain.invalid> wrote:

>
> Oh, and just to clarify my earlier suggestion of a 56 chr random code
> generator...my rough guestimate is that it would take all the computers

Ah, but another approach which might get there faster is to start with
a working small solution and then randomly mutate  it until a shorter
correct solution was found.

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/
Robert D. (Guest)
on 2007-06-04 00:38
(Received via mailing list)
On 6/3/07, S.Volkov <removed_email_address@domain.invalid> wrote:
> solution
> to handle addition of one more multiplyer, say 7-Gozz?
> Enterprise managers face luck of experienced programmers to execute routine
> maintenance tasks,
> so simple solution for simple task is a _must_.
But what is simple?
(1..100).each{ |x|
   print "Fuzz" if x%3 ==0
   print "Bizz" if x%5
   print x unless x%3*y%5==0
   puts ""
}
Is this simple?
Maybe you are right about the _must_ but then I feel that you are
wrong about the language.
I feel very *strongly* that Ruby is not a language for such code....
Let us maybe take a break, wait for James' resume and what other think
about this and than we might find a better understanding of this.
Boy who said this was a simple Quiz ;)

>
> >> Do you want the job or demonstration of your smartness?
> > This is not very smart a solution, it reflects some features of Ruby,
> > after all they are hiring a Ruby developer not a C or Perl developer.
> I didn't say it was smart solution :)
Hmm I do ;)

>
> >> imho: in any situation: KISS!
> > This is strong an expression, I will not take offense, others might.
> I'm terrybly sorry, no offense was intended (I forgot to mention this
> specifically in first place)!
> ashamed,
No that is exaggerated of course as I said no offense taken.
> Sergey V.
Do you like Star Trek?
Reminds me of the famous dialog between bones and Spock:
I am Spock you are bones ;)
>
>
>
>

Robert
Eric I. (Guest)
on 2007-06-04 00:41
(Received via mailing list)
Here's my solution.  It makes heavy use of the Ruby idiom of using the
&& and || operators to perform conditionals because a) they are short-
circuited and because b) && returns the right-hand-side when the left-
hand-side is a true value.

====
class Integer; def factor? n; self % n == 0; end; end

puts (1..100).map { |i| i.factor?(15)&&"FizzBuzz" || i.factor?
(3)&&"Fizz" || i.factor?(5)&&"Buzz" || i }
====

Eric

Are you interested in on-site Ruby training that uses well-designed,
real-world, hands-on exercises? http://LearnRuby.com
Robert D. (Guest)
on 2007-06-04 02:40
(Received via mailing list)
Sergey it is your fault if I cannot sleep ;), is this more readable ?

module Enumerable
  def change(to, &blk)
    map{ |x| blk.call(x) ? to : x }
  end
end # module Enumerable

puts (1..100).change(:FizzBuzz){ |x| x%15 == 0 }.change(:Fizz){ |x|
x%3 == 0 rescue false}.change(:Buzz){ |x| x%5 == 0 rescue false }
unknown (Guest)
on 2007-06-04 03:02
(Received via mailing list)
Hi --

On Mon, 4 Jun 2007, Robert D. wrote:

>> >> > puts '59'
>> >            31  32  Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44
>> Or:
>>
>>    puts %w{ 1 2 Fizz 4 ... }
> .join("\n")

You don't need that though; puts will puts each element in the array.


David
Sergey V. (Guest)
on 2007-06-04 03:38
(Received via mailing list)
----- Original Message -----
From: "Robert D." <removed_email_address@domain.invalid>
To: "ruby-talk ML" <removed_email_address@domain.invalid>
Sent: Sunday, June 03, 2007 6:38 PM
Subject: Re: [QUIZ] FizzBuzz (#126)


> Sergey it is your fault if I cannot sleep ;), is this more readable ?
relax, Robert, nobody hurt :)

> module Enumerable
>  def change(to, &blk)
>    map{ |x| blk.call(x) ? to : x }
>  end
> end # module Enumerable
>
> puts (1..100).change(:FizzBuzz){ |x| x%15 == 0 }.change(:Fizz){ |x|
> x%3 == 0 rescue false}.change(:Buzz){ |x| x%5 == 0 rescue false }
hard to make formal conclusions - there are no formal requirements,
nor context is well defined, I can share my own opinion and potential
concerns only:

- yes, indeed, this solution is more readable,
   compared to your Array-nested-tricky-indexed original solution;
- clear functional decomposition simplifies understanding, maintenance;
- it is easily expandable thanks to chain processing;
btw: I prefer different name for Enumerable method, ex: substitute_if;

Not so attractive in this solution:
- run-time/memory inefficient: each item is generates 4 times;
- memory inefficient: generates and stores in memory 4*original array
  (ex: not well suited for 10**9 length array);
- can not be adopted for stream processing (read - process - print);
- 'rescue' is for exceptional processing, should be avoided in normal
control flow;

Sergey V.
^-FakE-^ fake-or-dead (Guest)
on 2007-06-04 04:22
(Received via mailing list)
irb(main):282:0> a = (1..100).inject([]){|hash, x| hash[x-1] = x unless
x%3
==0 || x%5==0 || x%15==0 ; hash[x-1] = 'Fizz' if x%3==0 ; hash[x-1] =
'Buzz'
if x%5==0 ; hash[x-1] = 'FizzBuzz' if x%15==0 ; hash}

irb(main):283:0> a.each{|x| p x}

I like one line coding in ruby ^^

and sorry about my parameter name "hash" lazy to change >.<
Matthew M. (Guest)
on 2007-06-04 06:18
(Received via mailing list)
My solution, which is probably pretty similar to everyone else's
solution, but I didn't feel like being creative this weekend:

1.upto(100) do |i|
   puts case i % 15
      when 0 then "FizzBuzz"
      when 5, 10 then "Buzz"
      when 3, 6, 9, 12 then "Fizz"
      else i
   end
end
Jesse M. (Guest)
on 2007-06-04 06:20
(Received via mailing list)
Attached are my 7 attempts. Some are ok, some are crap. No golfing.
Matthew M. (Guest)
on 2007-06-04 06:24
(Received via mailing list)
Okay, one more solution that just came to mind:

1.upto(100) do |i|
   f, b = (i % 3).zero?, (i % 5).zero?
   puts "#{'Fizz' if f}#{'Buzz' if b}#{i unless (f or b)}"
end
James G. (Guest)
on 2007-06-04 07:23
(Received via mailing list)
On Jun 1, 2007, at 10:37 PM, Morton G. wrote:

> On Jun 1, 2007, at 8:28 AM, Ruby Q. wrote:
>
>>   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”.
>
> I would not be surprised if this quiz produces the most submissions
> of any quiz ever.

Good prediction.  You were right.

James Edward G. II
Robert D. (Guest)
on 2007-06-04 09:02
(Received via mailing list)
On 6/3/07, Sergey V. <removed_email_address@domain.invalid> wrote:
> > module Enumerable
>
> - yes, indeed, this solution is more readable,
>    compared to your Array-nested-tricky-indexed original solution;
> - clear functional decomposition simplifies understanding, maintenance;
> - it is easily expandable thanks to chain processing;
I feel good ;)
> btw: I prefer different name for Enumerable method, ex: substitute_if;
agreed and alias to change_if then there will be a
substitute/change_unless too.
>
> Not so attractive in this solution:
> - run-time/memory inefficient: each item is generates 4 times;
> - memory inefficient: generates and stores in memory 4*original array
Good point a change_if! might have been better.
>   (ex: not well suited for 10**9 length array);
Too bad ;)
> - can not be adopted for stream processing (read - process - print);
good point, but is that not the price to pay for functional
decomposition?
> - 'rescue' is for exceptional processing, should be avoided in normal
> control flow;
I gotta think about this, I tend to agree for
begin
rescue ...
end
the inline form seems too compact for that and I do not consider it
control flow but rather a logical operator like
expression or_if_that_does_not_work other
but you do have a point.

Thx for your thoughts AAMOF you make me think that the discussion of
your solution with the recruiters is very important too.

Cheers
Robert
Morton G. (Guest)
on 2007-06-04 09:49
(Received via mailing list)
On Jun 3, 2007, at 11:22 PM, James Edward G. II wrote:

>> I would not be surprised if this quiz produces the most
>> submissions of any quiz ever.
>
> Good prediction.  You were right.

Well, if I'm on a roll, perhaps you'll tolerate some further semi-
random remarks about this quiz.

I guess a lot of us want new jobs.

I really like Fred P.' solution. A fine example of pursuing the
KISS principle right into the ground. I wish I'd thought of it.

I don't envy you your job of having to summarize all these submissions.

Are the above remarks facetious? Mostly but not entirely.

Regards, Morton
Ruben M. (Guest)
on 2007-06-04 09:56
(Received via mailing list)
On Jun 1, 7:28 am, Ruby Q. <removed_email_address@domain.invalid> wrote:
> The three rules of Ruby Q.:

Interesting quiz, as usual.

I don't really have experience applying for jobs, but my own
experience tells me that when writing code, you should write it for
others to read it, change it, manage it and/or throw it away.

The first question that jumps into my mind is: why would a job
interviewer wanted me to write me such a program? What the heck is a
'FizzBuzz'?

Probably is a company secret. To me, it looks like a little useless
noise coming from somewhere.

# Class that takes numbers and transforms them into a symbol
# specified for the user

class UselessSoundMaker

  attr_accessor :sounds

  def initialize(args)
    @sounds = args
  end

  def add_sounds(args)
    @sounds.update(args)
  end

  def display(range = 1..100)
    for number in range
      if (multiples = @sounds.keys.select{|m| number % m == 0}).empty?
        puts number
      else
        puts multiples.sort.collect{|m| @sounds[m]}.join
      end
    end
  end

end

fizzbuzz = UselessSoundMaker.new(3 => 'Fizz', 5 => 'Buzz')
fizzbuzz.display

foobar = UselessSoundMaker.new(3 => 'Foo', 4 => 'Bar', 5 => 'Baz')
foobar.display(1..50)

beepbeep = UselessSoundMaker.new(10 => "\a")
beepbeep.display(1..100)



Thanks again for the quizes.

Ruben M..
__________________________________________

Dictionary is the only place that success comes before work. - Vince
Lombardi
Robert D. (Guest)
on 2007-06-04 11:24
(Received via mailing list)
On 6/4/07, Morton G. <removed_email_address@domain.invalid> wrote:
> On Jun 3, 2007, at 11:22 PM, James Edward G. II wrote:
>

>
> I really like Fred P.' solution.
Honestly the idea is awesome, but he should have taken care to get the
syntax right. I think it is not a good solution in the exact context
but a good distribution for us to have fun.
> A fine example of pursuing the
> KISS principle right into the ground. I wish I'd thought of it.
The KISS principle was already embraced by nobody less than Albert
Einstein who said "As simple(*) as possible, but not simpler!"
the last part being quite irrelevant in our case.
BUT does the merciless application of KISS give you the warm fuzzy
feeling?
I believe - idiotically and idealistically ( they often come in pairs
) - that this warm fuzzy feeling is necessary to be productive. So
emotionally I dislike KISS somehow but I have to admit that I learnt a
lot while being put on my place ;)

>
> I don't envy you your job of having to summarize all these submissions.

Sure and even more so, as we are already discussing solutions, which
have never seen before, and might even be bad form when I think about
it -maybe with the exception of the one liners. But this Quiz is
special :)

Knowing James a little bit he will find a practical approach making
his life a little bit easier and still giving a good resume, if he is
doing it himself BTW.


>
> Are the above remarks facetious? Mostly but not entirely.
>
> Regards, Morton
>
(*) I daresay that "simple" is not well defined though :)

Cheers
Robert
Daniel M. (Guest)
on 2007-06-04 18:13
(Received via mailing list)
James Edward G. II <removed_email_address@domain.invalid> writes:

> On Jun 1, 2007, at 10:37 PM, Morton G. wrote:
>> I would not be surprised if this quiz produces the most submissions
>> of any quiz ever.
>
> Good prediction.  You were right.

And yet, no one has so far posted a solution involving callcc or
threads. (unless I missed it)

I may have to go back for another round of interviews at
CompuGlobalMegaTech...
Robert D. (Guest)
on 2007-06-04 18:46
(Received via mailing list)
On 6/4/07, Daniel M. <removed_email_address@domain.invalid> wrote:
> James Edward G. II <removed_email_address@domain.invalid> writes:
>
> > On Jun 1, 2007, at 10:37 PM, Morton G. wrote:
> >> I would not be surprised if this quiz produces the most submissions
> >> of any quiz ever.
> >
> > Good prediction.  You were right.
>
> And yet, no one has so far posted a solution involving callcc or
> threads. (unless I missed it)
and inject (unless I midded it;)
Ball, Donald A Jr (Library) (Guest)
on 2007-06-04 18:55
(Received via mailing list)
I'll add my solutions to the thundering horde. My first solution was
moderately clever:

puts
(1..100).map{|n|[[3,'fizz'],[5,'buzz']].inject(n){|s,a|s.is_a?(Fixnum)?s
=a[1]:s+=a[1] if n%a[0]==0;s}}

then I tried to use as few characters as possible:

puts (1..100).map{|n|n%15==0?:fizzbuzz:n%5==0?:buzz:n%3==0?:fizz:n}
puts (1..100).map{|n|n%15>0?n%5>0?n%3>0?n:'fizz':'buzz':'fizzbuzz'}

- donald
Robert D. (Guest)
on 2007-06-04 19:01
(Received via mailing list)
On 6/4/07, Ball, Donald A Jr (Library) <removed_email_address@domain.invalid>
wrote:
> puts (1..100).map{|n|n%15>0?n%5>0?n%3>0?n:'fizz':'buzz':'fizzbuzz'}
>
> - donald
>
>
That takes care of inject, what a great response time Donald ;)!
Robert
Joel VanderWerf (Guest)
on 2007-06-04 19:37
(Received via mailing list)
CHubas wrote:
...
> The first question that jumps into my mind is: why would a job
> interviewer wanted me to write me such a program? What the heck is a
> 'FizzBuzz'?

Didn't you hear? Google is developing a soft drink containing nothing
but carbonation and caffeine.
Daniel M. (Guest)
on 2007-06-04 20:05
(Received via mailing list)
"Robert D." <removed_email_address@domain.invalid> writes:

> and inject (unless I midded it;)

Aside from the one posted just after you sent this, there actually
have been one or two solutions using inject already, but nothing that
really seems to take advantage of it.  Of course, when I try to
construct such a solution, I can't do much better - inject is a
relatively specialized tool, and works best when the output of inject
is then useful in some material way, rather than when it's being
executed purely for its side effects.

I'm going to think on this some more...
Ruben M. (Guest)
on 2007-06-04 21:21
(Received via mailing list)
> Aside from the one posted just after you sent this, there actually
> have been one or two solutions using inject already, but nothing that
> really seems to take advantage of it.  Of course, when I try to
> construct such a solution, I can't do much better - inject is a
> relatively specialized tool, and works best when the output of inject
> is then useful in some material way, rather than when it's being
> executed purely for its side effects.

IMO, the only thing you would need inject here is to store the output
of the program in a string rather than just print it. So, consider it
another solution.

str = (1..100).inject('') do |s, n|
  s + (
    if (n3 = n % 3 == 0) & (n5 = n % 5 == 0)
      "FizzBuzz"
    elsif n3
      "Fizz"
    elsif n5
      "Buzz"
    else
      n.to_s
    end
  ) + "/n"
end

puts str


Excuse my "/n", but I cannot find the backslash in this crappy
computer ><

> Didn't you hear? Google is developing a soft drink containing nothing
> but carbonation and caffeine.

Yay! Google drinks!

__________________________________________

Dictionary is the only place that success comes before work. - Vince
Lombardi
Warren B. (Guest)
on 2007-06-04 21:31
(Received via mailing list)
> Didn't you hear? Google is developing a soft drink
> containing nothing but carbonation and caffeine.

    I hear the original name was "Gurgle", but apparently they're shying
away from the "cute but meaningless" names now.
Morton G. (Guest)
on 2007-06-04 23:46
(Received via mailing list)
On Jun 4, 2007, at 3:24 AM, Robert D. wrote:

> Honestly the idea is awesome, but he should have taken care to get the
> syntax right. I think it is not a good solution in the exact context
> but a good distribution for us to have fun.

If I were on the hiring side in the scenario put forth in the quiz
description, I would look more favorably on a job candidate who came
up with Phillips' solution than one who came up with a more
pedestrian one such my own.

> Einstein who said "As simple(*) as possible, but not simpler!"
> the last part being quite irrelevant in our case.
> BUT does the merciless application of KISS give you the warm fuzzy
> feeling?

No, but it makes me laugh when I see it. I admire Phillips' solution
not because I'm a big fan of KISS[*] but for its zen-like qualities
-- the out-of-the-box thinking it displays.

Regards, Morton

[*] Regard the phrase

    pursuing the KISS principle right into the ground

and visualize what happens in a WW II movie when one airplane pursues
another into the ground.

And I don't like the rock group either.
Rick D. (Guest)
on 2007-06-05 00:33
(Received via mailing list)
On 6/4/07, Morton G. <removed_email_address@domain.invalid> wrote:
> On Jun 4, 2007, at 3:24 AM, Robert D. wrote:
>
> > Honestly the idea is awesome, but he should have taken care to get the
> > syntax right. I think it is not a good solution in the exact context
> > but a good distribution for us to have fun.
>
> If I were on the hiring side in the scenario put forth in the quiz
> description, I would look more favorably on a job candidate who came
> up with Phillips' solution than one who came up with a more
> pedestrian one such my own.

Perhaps a particular potential employer might see it that way. I
suspect that most wouldn't, although the good ones would take it as in
indication not of programming but of interpersonal skills.

The elephant in the room in the situation posited by this quiz is that
after a candidate provides some solution, it becomes more of a
psychological compatibility test than a programming skill test.

Some employers/clients might be looking for an employee/consultant who
can program and communicate clearly, probably a good choice in most
situations.

Others might have a liking for overly clever programmers.  This might
be a good choice for them, more likely not. Personally I'd rather work
for/with the first kind of employer/client than the latter.  I tend to
view a interview, from either side of the table, as a dialog searching
for compatibility rather a one-sided interrogation.

Fred P. gives a nice whimsical 'solution', it's clever and funny
with the quirky take things literally with an unexpected twist sense
of humor which characterized the late great Gracie Allen, a style
which I personally love and emulate.

Now if I were the potential hirer, thought this whole fizzbuzz test
were a good idean, which is not likely by the way, and I got such a
reply, I'd probably respond by saying "okay, wise guy, now show me how
you'd really do it."

Some of us can program well and communicate clearly, others can write
tricky code, some of us can be humorous. Each of us can all probably
do all three to varying extents.  The trick is choosing the right
combination for the occasion, whether we are interviewing or on the
job.


--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/
Daniel M. (Guest)
on 2007-06-05 06:04
(Received via mailing list)
# A> I CAN HAS INTERVIEW?  I ARE ADVANCED PROGRAMMER.
#
# B> O HAI. U CAN HAS CALLCC?  GIMMEH FIZZBUZZ SOLUTION!

f_=b_=nil
callcc { |o|
  loop do
    o = callcc {|i|f_=i; o[:Fizz]}
    2.times{o = callcc{|i|f_=i;o[]}}
  end
}
callcc { |o,n|
  loop do
    o,n = callcc {|i|b_=i; o["#{n}Buzz"]}
    4.times{o,n = callcc{|i|b_=i;o[n]}}
  end
}
f = lambda{callcc{|i|f_[i]}}
b = lambda{|n|callcc{|i|b_[i,n]}}
1.upto(100){|i|puts b[f[]]||i}

# B> KTHX. U CAN HAS THREADS?

a = nil
f = Thread.new { loop { sleep 3; print :Fizz; a = nil } }
b = Thread.new { sleep 0.2; loop { sleep 5; print :Buzz; a = nil } }
sleep 0.5
1.upto(100) {|i| a=i; sleep 1; puts "#{a}"}

# B> LOL. UR CODE IS TEH SLOW
#
# A> I MADE U ONE WITH SEMAPHORE BUT I EATED IT.
#
# B> U CAN HAS INJECT?

a='_//_/_//_/_'.gsub('_','Fizz').split('/')
b='/_///_//_'.gsub('_','Buzz').split('/')

class Array
 def roll
   self.push(self.shift).last
 end
end

(1..101).select{|n|(n%5)*(n%3)>0}.inject(0){|r,n|
  puts "#{a.roll}#{b.roll}" while n>r+=1
  puts n if n<99
  r
}

# B> I SEE WHAT YOU DID THERE
#
# A> WHAT YOU SAY !!
#
# B> U CAN HAS INJECT, RLY? NOT ALL SIDE EFFECTZ?

(1..100).inject("x"){|p,n|
  p.sub(/^((?:(?:x[^x]*){3})*)$/,'\1Fizz').
    sub(/^((?:(?:x[^x]*){5})*)$/,'\1Buzz').
    sub(/x$/,"x#{n}") + 'x'
}.sub(/^x/,'').gsub(/x/,"\n").display

# B> KTHXBYE
#
# A> I CAN HAS PHONE CALL? PLZ?
Todd B. (Guest)
on 2007-06-05 10:25
(Received via mailing list)
On 6/4/07, Morton G. <removed_email_address@domain.invalid> wrote:
> > Einstein who said "As simple(*) as possible, but not simpler!"
> > the last part being quite irrelevant in our case.
> > BUT does the merciless application of KISS give you the warm fuzzy
> > feeling?
>
> No, but it makes me laugh when I see it. I admire Phillips' solution
> not because I'm a big fan of KISS[*] but for its zen-like qualities
> -- the out-of-the-box thinking it displays.

Phillips' solution isn't so much of an example of KISS as it is a
sense of humor.  We can all build mountains one grain of sand at a
time :)

In any case; one point for satisfying (almost) the criteria and one
point for being the sole person to do it that way (I doubt anyone else
thought of that solution).
(Guest)
on 2007-06-05 14:06
(Received via mailing list)
I disagree.  I challenged several of my coworkers to solve FizzBuzz a
few weeks ago.  All of the solutions were pretty much the same except
the one from our lead DBA.  He solved the problem in a stored
procedure without using a cursor.  It was exceptionally clever and
totally horrific at the same time.  We gave him the "Most
Inappropriate Use of Set Theory" award.
Paul N. (Guest)
on 2007-06-05 16:56
(Received via mailing list)
On Jun 5, 6:01 am, "removed_email_address@domain.invalid" 
<removed_email_address@domain.invalid> wrote:
>
> > I do not think there is a lot of room for cleverness in the FizzBuzz
> > problem.  (Actually, I hope I am wrong and we see lots more
> > suggestions for Extra Fun like Peter's.)  My understanding is that
> > FizzBuzz was intended to screen out candidates that could *not* come
> > up with working code in a few minutes.
>
> > Regards,
>
> > Paul.

As the last few days have shown, there *are* clever ways of solving
FizzBuzz.  However, IMHO, there are very few that would be appropriate
for the stated scenario of a job interview.

My tendency would be to create the simplest thing that could possibly
work in clear and readable and maintainable code.  After all,
employers want someone who is smart, but also want someone who gets
things done efficiently.  Possibly, with just the right interviewer, I
might discus various solutions pros and cons, which might be optimized
for particular scenarios, etc.

Maybe I just haven't interviewed the right sort of employers that
would appreciate such creativity...

Regards,

Paul.
Robert D. (Guest)
on 2007-06-05 17:06
(Received via mailing list)
On 6/5/07, Paul N. <removed_email_address@domain.invalid> wrote:
> >
>
>
> Maybe I just haven't interviewed the right sort of employers that
> would appreciate such creativity...
>
> Regards,
>
> Paul.
>
>
>

Actually I feel that somehow - sorry I have said this before, but I am
not sure it was heard ;) - this is about a job, yes but with R u b y.
And if I were to hire a Ruby programmer and the guy just writes some
Java/C/Perl/OCaml or whatever code, expressed in Ruby, will I take
him?

So whatever is said about simple and maintainable and psychological
impact for sure is clever stuff coming from experience I am lacking.
But many of you are forgetting the   R u b y  part nonetheless.

Cheers
Robert
Rob B. (Guest)
on 2007-06-05 18:30
(Received via mailing list)
On Jun 5, 2007, at 9:04 AM, Robert D. wrote:
>> >
>> > > Regards,
>> employers want someone who is smart, but also want someone who gets
>>
> But many of you are forgetting the   R u b y  part nonetheless.
>
> Cheers
> Robert
>
> --
> You see things; and you say Why?
> But I dream things that never were; and I say Why not?
> -- George Bernard Shaw

Regardless of how simple or clever the code, if it isn't
syntactically correct or fails to use common Ruby idioms, it fails as
an interview response.

i=1; while i <= 100; ...; i += 1; end  #  BZZZT! Sorry, thanks for
playing.
1.upto(100) do |i| ... end  # DING!
(1..100).each {|i| ... }  # DING!

Any more than one bug and I'd say the interview was over (and ANY bug
if actually using irb or ruby to run the code would be too many).

The exact format of the output wasn't rigorously defined so I'd
expect a reasonable interpretation (unless the solution offered
couldn't be simply and obviously changed to add/remove spacing,
newlines, quotes, capitalization, etc.).

If I were giving this test, extra credit would be earned for knowing
that i%15 == 0 is equivalent to (i%3==0 && i%5==0) because I can't
imagine a programmer being very good without a firm grasp of some
math as basic as this.

If the interviewee immediately starting golfing, that'd lose credit,
but noticing simple, incremental improvement would be positive. For
example, noticing the use of case..end's value as an expression:

case
when i%15 == 0
   puts "FizzBuzz"
when i%3 == 0
   puts ...

becoming:

puts case
      when i%15 == 0 : "FizzBuzz"
      when i%3 == 0 : ...

Overall, the volume of responses to the quiz is interesting only when
it doesn't degrade to golfing.  (My own straight-forward solution
incrementally shrinks down to 69 bytes, but I have no interest in
squeezing it any more -- it wouldn't be readable -- and anyone who
used the ?d == 100 trick in an interview should be shown the door!)

-Rob

Rob B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
James G. (Guest)
on 2007-06-05 18:44
(Received via mailing list)
On Jun 5, 2007, at 9:29 AM, Rob B. wrote:

> If I were giving this test, extra credit would be earned for
> knowing that i%15 == 0 is equivalent to (i%3==0 && i%5==0) because
> I can't imagine a programmer being very good without a firm grasp
> of some math as basic as this.

I guess you wouldn't hire me.  I used the double-test form because I
thought it was self documenting.

James Edward G. II
Rob B. (Guest)
on 2007-06-05 18:51
(Received via mailing list)
On Jun 5, 2007, at 10:43 AM, James Edward G. II wrote:
> James Edward G. II
I said "extra credit" (you didn't use the ?d thing, right? ;-)

It'll be interesting to see how you summarize all of this.

Thanks James,

-Rob

Rob B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
Jesse M. (Guest)
on 2007-06-05 18:58
(Received via mailing list)
On Sunday 03 June 2007 11:32, Joshua B. wrote:
> Mathematically speaking, finding the shortest/optimal solution to any
> programming challenge is an NP problem. It might be fun to do a follow
> up quiz where the goal is to write a code generator that can find the
> elusive 56 byte golfing solution to the FizzBuzz quiz. If one were to
> simply write a random ASCII string generator and test every possible 56
> byte string, it would take less than 95^56 (or 5.656e110) iterations...
>
> ...or would that quiz be too hard?

Its much worse than NP - its uncomputable. You'd run into the halting
problem doing the tests.
Sun P. (Guest)
on 2007-06-05 19:07
(Received via mailing list)
I've attempted to create random code generator before, but soon gave up.

Will there be any ways to optimize the generator so that we can
practically
use it?

2007/6/5, Jesse M. <removed_email_address@domain.invalid>:
Daniel F. (Guest)
on 2007-06-06 03:52
(Received via mailing list)
Here is my solution:

http://pastie.caboo.se/68127

for i in 1..100
mod3 = (i % 3 == 0)
mod5 = (i % 5 == 0)

print "Fizz" if mod3
print "Buzz" if mod5
print i if !mod3 && !mod5

puts ""
end

Dan Finnie
Stephen S. (Guest)
on 2007-06-06 05:38
(Received via mailing list)
Is there a short circuit AND in ruby?

Just wondering...
James G. (Guest)
on 2007-06-06 05:42
(Received via mailing list)
On Jun 5, 2007, at 8:37 PM, Stephen S. wrote:

> Is there a short circuit AND in ruby?

&& does short-circuit.

James Edward G. II
Joel VanderWerf (Guest)
on 2007-06-06 06:44
(Received via mailing list)
James Edward G. II wrote:
> On Jun 5, 2007, at 8:37 PM, Stephen S. wrote:
>
>> Is there a short circuit AND in ruby?
>
> && does short-circuit.

as does "and", but beware the lower precedence:


irb(main):010:0> x = false && 3; x
=> false
irb(main):011:0> x = true && 3; x
=> 3
irb(main):012:0> x = false and 3; x
=> false
irb(main):013:0> x = true and 3; x
=> true
irb(main):014:0> x = (false and 3); x
=> false
irb(main):015:0> x = (true and 3); x
=> 3
Morton G. (Guest)
on 2007-06-06 17:50
(Received via mailing list)
After completing my Ruby Q. submission, I decided to implement
FizzBuzz in Mathematica. Here is the first version that I wrote.

f[x_] := Print["FizzBuzz"] /; Mod[x, 15] == 0
f[x_] := Print["Buzz"] /; Mod[x, 5] == 0
f[x_] := Print["Fizz"] /; Mod[x, 3] == 0
f[x_] := Print[x]
f /@ Range[100];

I think this example pretty well gives the flavor of Mathematica.
Note that no explicit flow control is needed. Of course, Mathematica,
like Ruby, allows one to write FizzBuzz in many ways, including some
that would look much more procedural and others that are more
functional. Here is an example of the latter.

MapThread[(f[z_] := Print[#1] /; Mod[z, #2] == 0) &,
  {{"FizzBuzz", "Buzz", "Fizz"}, {15, 5, 3}}];
f[x_] := Print[x]
f /@ Range[100];

In this second example, the MapThread generates three lines of code
equivalent to the first three lines of the first example.

I apologize to anyone who finds this off topic post distracting, but
I am hoping at least some readers of mailing list will find it
interesting to see FizzBuzz in a language very different both from
Ruby and all the well-known static, procedural languages.

Regards, Morton
Joshua B. (Guest)
on 2007-06-06 21:31
I hope it's not too late for a new submission!

So, when I first read this quiz, it didn't seem like enough of a
challenge. Immediately, I wondered if someone would come up with a
threaded answer, but then everyone started playing golf, and I got a bit
caught up in that...

Well, since no one did go for the threaded solution (and since I needed
to brush up on my threading skills anyway), I give you THE THREADED
FIZZBUZZER!!! (no, not the dreaded...threaded...) ;)

#!/usr/bin/env ruby -w

require 'monitor'
class FizzThreader
  attr_reader :counting

  def initialize
    @counting = 1
    @fizz_went = false
    @buzz_went = false
    @numbers_went = false
    @done_counting = false
    @output = ''
    @output.extend(MonitorMixin)
  end

  def fizz
    Thread.new do
      loop do
        @output.synchronize do
          if !@fizz_went && !@buzz_went && !@numbers_went
            @output << 'Fizz' if @counting%3 == 0
            @fizz_went = true
          end
        end
        break if @done_counting && @fizz_went
      end
    end
  end

  def buzz
    Thread.new do
      loop do
        @output.synchronize do
          if @fizz_went && !@buzz_went && !@numbers_went
            @output << 'Buzz' if @counting%5 == 0
            @buzz_went = true
          end
        end
        break if @done_counting && @buzz_went
      end
    end
  end

  def numbers
    Thread.new do
      loop do
        @output.synchronize do
          if @fizz_went && @buzz_went && !@numbers_went
            @output << @counting.to_s unless (@counting%3 == 0 ||
@counting%5 == 0)
            @numbers_went = true
          end
        end
        break if @done_counting && @numbers_went
      end
    end
  end

  def count_upto(i)
    Thread.new do
      loop do
        @output.synchronize do
          if @fizz_went && @buzz_went && @numbers_went
            @output << "\n"
            @counting += 1
            @done_counting = true if @counting >= i
            @fizz_went = false
            @buzz_went = false
            @numbers_went = false
          end
        end
        break if @done_counting
      end
    end
  end

  def start_counting_upto(i)
    @counting_threads = []
    @counting_threads << fizz
    @counting_threads << buzz
    @counting_threads << numbers
    @counting_threads << count_upto(i)
    @counting_threads.each {|thr| thr.join}
    @output
  end

end

fizzy_threads = FizzThreader.new
puts fizzy_threads.start_counting_upto(100)
Morton G. (Guest)
on 2007-06-06 22:06
(Received via mailing list)
Quiz 126 is now the most popular Ruby Q. ever. Quiz 84 was the
previous champion. All Rubyists will grasp the significance of 126 -
84 = 42 :)

Ain't numerology fun?

Regards, Morton
Rob B. (Guest)
on 2007-06-06 22:34
(Received via mailing list)
On Jun 6, 2007, at 2:05 PM, Morton G. wrote:
> Quiz 126 is now the most popular Ruby Q. ever. Quiz 84 was the
> previous champion. All Rubyists will grasp the significance of 126
> - 84 = 42 :)
>
> Ain't numerology fun?
>
> Regards, Morton

puts "very popular" if RubyQuiz.number % 42 == 0

-Rob

Rob B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
Enrique Comba R. (Guest)
on 2007-06-06 22:38
(Received via mailing list)
On 6 Jun 2007, at 20:05, Morton G. wrote:

> Quiz 126 is now the most popular Ruby Q. ever. Quiz 84 was the
> previous champion. All Rubyists will grasp the significance of 126
> - 84 = 42 :)
>
> Ain't numerology fun?
>
> Regards, Morton

Hmmmm 42...

The answer to all questions...

I wonder if on the next (and subsequent ruby quizzes) I could just
answer 42 :)


----
Enrique Comba R.
removed_email_address@domain.invalid

I always thought Smalltalk would beat Java, I just didn't know it
would be called 'Ruby' when it did.
-- Kent Beck
Morton G. (Guest)
on 2007-06-06 22:42
(Received via mailing list)
On Jun 6, 2007, at 2:33 PM, Rob B. wrote:

> On Jun 6, 2007, at 2:05 PM, Morton G. wrote:
>> Quiz 126 is now the most popular Ruby Q. ever. Quiz 84 was the
>> previous champion. All Rubyists will grasp the significance of 126
>> - 84 = 42 :)
>>
>> Ain't numerology fun?
>>
>> Regards, Morton
>
> puts "very popular" if RubyQuiz.number % 42 == 0

It's too bad, but that theory fails. I wish it were otherwise, but
Ruby Q. 42 was (I think) the least popular of all time.

Regards, Morton
Brian A. (Guest)
on 2007-06-07 01:35
(Received via mailing list)
On Sun, 03 Jun 2007 13:55:56 -0400, S.Volkov wrote:

>> print "FizzBuzz".
> =end
> def sol1 maxn=100
>     end
>             s = "FizzBuzz"
> puts '### TC1a'
>             if s.empty? : i else s end
>         s = "Fizz" if (n%3).zero?
>     def toFizzBuzz
>
> 1.upto(?d){|i|i%3<1&&x=:Fizz;puts i%5<1?"#{x}Buzz":x||i}# 56
Another 56 byter :)
puts `seq 100|sed -e'5~5s/.*/Buzz/;3~3s/^[0-9]*/Fizz/'`
James G. (Guest)
on 2007-06-07 02:19
(Received via mailing list)
On Jun 6, 2007, at 12:31 PM, Joshua B. wrote:

> Well, since no one did go for the threaded solution...

There was one.  See:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/...

James Edward G. II
Gavin K. (Guest)
on 2007-06-07 02:36
(Received via mailing list)
On Jun 4, 8:03 pm, Daniel M. <removed_email_address@domain.invalid> wrote:
> # A> I CAN HAS INTERVIEW?  I ARE ADVANCED PROGRAMMER.
> #
> # B> O HAI. U CAN HAS CALLCC?  GIMMEH FIZZBUZZ SOLUTION!

ROFLMAOBBQ!
Well done!


I particularly like the 3 meme crossover in:

> # B> I SEE WHAT YOU DID THERE
> #
> # A> WHAT YOU SAY !!
> #
> # B> U CAN HAS INJECT, RLY? NOT ALL SIDE EFFECTZ?


Oh, and your solutions are ftw, too. :)
Gavin K. (Guest)
on 2007-06-07 02:56
(Received via mailing list)
On Jun 6, 4:34 pm, Phrogz <removed_email_address@domain.invalid> wrote:
> On Jun 4, 8:03 pm, Daniel M. <removed_email_address@domain.invalid> wrote:
>
> > # A> I CAN HAS INTERVIEW?  I ARE ADVANCED PROGRAMMER.
> > #
> > # B> O HAI. U CAN HAS CALLCC?  GIMMEH FIZZBUZZ SOLUTION!
>
> ROFLMAOBBQ!
> Well done!

That reminds me...

For those that haven't seen it, our brethren/enemy Pythonistas don't
have to reserve the above lolcat syntax for comments only:

http://www.dalkescientific.com/writings/diary/arch...

They are winning the race to amusingly obfuscated code!
Joshua B. (Guest)
on 2007-06-07 03:05
James G. wrote:
> On Jun 6, 2007, at 12:31 PM, Joshua B. wrote:
>
>> Well, since no one did go for the threaded solution...
>
> There was one.  See:
>
> http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/...
>
> James Edward G. II

Yeah, I noticed that shortly after I sent in mine. Ok, so I can't claim
the first threaded solution...but maybe at least the first "safely"
threaded solution? (i.e. try running the aforementioned solution in
irb...)
Ryan S. (Guest)
on 2007-06-07 15:27
(Received via mailing list)
My solution that I'd submit in an interview:

1.upto(100) do |i|
  buffer = i % 3 == 0 ? "Fizz" : nil
  buffer = buffer.to_s + "Buzz" if i % 5 == 0
  p buffer || i
end

--RYAN
Paddy3118 (Guest)
on 2007-06-10 09:15
(Received via mailing list)
On Jun 3, 5:43 pm, darren kirby <removed_email_address@domain.invalid> wrote:
>     print "Fizz "
>     elif n % 3 == 0:
>         sys.stdout.write("Fizz ")
>     elif n % 5 == 0:
>         sys.stdout.write("Buzz ")
>     else: sys.stdout.write("%i " % n)
> print

A slight clean-up of the Python code.
The trailing comma on the print will
add a space as separator.

# fizz.py using print
import sys
for n in range(1, int(sys.argv[1])+1):
    if n % 15 == 0:
        print "FizzBuzz",
    if n % 3 == 0:
        print "Fizz",
    if n % 5 == 0:
        print "Buzz",
    else:
        print n,
print


- Paddy.
Paddy3118 (Guest)
on 2007-06-10 09:21
(Received via mailing list)
On Jun 10, 6:14 am, Paddy3118 <removed_email_address@domain.invalid> wrote:
> >   if n % 15 == 0
> > # fizz.py
>
>         print "Fizz",
>     if n % 5 == 0:
>         print "Buzz",
>     else:
>         print n,
> print
>
> - Paddy.

I'm a Dork!
I posted my scriblings instead of:

# fizz.py using print
import sys
for n in range(1, int(sys.argv[1])+1):
    if n % 15 == 0:
        print "FizzBuzz"
    elif n % 3 == 0:
        print "Fizz"
    elif n % 5 == 0:
        print "Buzz"
    else:
        print n
print
Martin DeMello (Guest)
on 2007-09-26 01:04
(Received via mailing list)
On 6/6/07, Brad P. <removed_email_address@domain.invalid> wrote:
>
> for i in 1..100 do
>      if i == f
>          if i == b
>              puts "fizzbuzz"
>              f += 3
>              b += 5

Sadly, + (and hence +=) is a method call too :)

martin
Brad P. (Guest)
on 2007-09-26 01:07
(Received via mailing list)
Martin DeMello wrote:
>> b = 5
> martin
>

True but I think the overall method count will be lower
as the addition ops are only executed when the main
counter meets the correct conditions instead of
redundantly calculating the modulo for each loop
iteration.
Brad P. (Guest)
on 2007-09-26 01:09
(Received via mailing list)
I am sure I just submitted this with a lengthy explanation but it
didn't appear in the list ??? So here it is again with no explanation
except that it minimizes method calls as much as possible by
avoiding modulo operation and maintaining separate counters.


f = 3
b = 5

for i in 1..100 do
     if i == f
         if i == b
             puts "fizzbuzz"
             f += 3
             b += 5
         else
             puts "fizz"
             f += 3
         end
     elsif i == b
         puts "buzz"
         b += 5
     else
         puts i
     end
end
This topic is locked and can not be replied to.