[QUIZ] FizzBuzz (#126)

R

Robert Dober

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
That takes care of inject, what a great response time Donald ;)!
Robert
 
J

Joel VanderWerf

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

Daniel Martin

Robert Dober said:
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...
 
C

CHubas

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
 
W

Warren Brown

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

Morton Goldberg

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

Rick DeNatale

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

Daniel Martin

# 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_}}
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?
 
T

Todd Benson

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

spooork

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

Paul Novak

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.

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

Robert Dober

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.

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
 
R

Rob Biedenharn

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

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 Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 
J

James Edward Gray II

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 Gray II
 
R

Rob Biedenharn

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

James Edward Gray 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 Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 
J

Jesse Merriman

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

Joel VanderWerf

James said:
&& 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
 
B

Brad Phelan

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top