[QUIZ] FizzBuzz (#126)

S

S.Volkov

Daniel Martin said:
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
 
P

Patrick Hurley

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
 
B

Brian Candler

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 :-(
 
A

Ari Brown

My solution has 75 characters, damn, I will have another look at it!

to answer ari's questions:


try this:

case
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?
 
T

Todd Benson

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

Sergey Volkov

----- Original Message -----
From: "Ari Brown" <[email protected]>
To: "ruby-talk ML" <[email protected]>
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
 
P

Patrick Hurley

----- Original Message -----
From: "Ari Brown" <[email protected]>
To: "ruby-talk ML" <[email protected]>
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

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
 
R

Robert Dober

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? :)
No idea, the recruiters are not here yet, they will arrive in an hour
and half ;)
R.
 
S

Stefan Rusterholz

S.Volkov said:
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
 
E

Enrique Comba Riepenhausen

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 Riepenhausen
(e-mail address removed)

I always thought Smalltalk would beat Java, I just didn't know it
would be called 'Ruby' when it did.
-- Kent Beck
 
S

Sharon Phillips

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
 
R

Robert Dober

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
 
R

Robert Dober

YW5kIGlmIEkgZG8gbm90IDspCgpyZXF1aXJlICd6bGliJwpwdXRzIFpsaWI6Okd6aXBSZWFkZXIu
bmV3KERBVEEpLnJlYWQKX19FTkRfXwo/N2BG4pi74pmlb2sub3V0IF3DjjvimavimaVFw5HDnifi
hqhjw4B8w5rCtsOZS+KWrD9mVlnihqg5xpLimLsuJcObSMOcwrPDpiA5esKvw6tzQ8OmeMK8wr8t
w7PCtDnDvMK+WcO/wrXDrsO3YuKInznCr8OfTHEsw6dRd+KXhAoiw4R1TsORwqHDuMOfw4YoccOC
wrjDieKGkeKGlG42ST4gI8OFJihJw5rCpMOZNjrCu8OZdsOaNjrCu8OYwrYlTT42PsKiwqPDjWZp
M3TCrMOY4pmAJUs+NT7Co8Ojw43DpmlzdMK8w5jimLvCpUhbNFsg4oC8w43DtuKYugrDvcOYcsKy
4pi64pi7CgotLSAKWW91IHNlZSB0aGluZ3M7IGFuZCB5b3Ugc2F5IFdoeT8KQnV0IEkgZHJlYW0g
dGhpbmdzIHRoYXQgbmV2ZXIgd2VyZTsgYW5kIEkgc2F5IFdoeSBub3Q/CgotLSBHZW9yZ2UgQmVy
bmFyZCBTaGF3Cg==
 
A

anansi

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
 
C

Craig Demyanovich

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
 
M

Morton Goldberg

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
 
T

Todd Benson

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

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
 
D

Don Levan

Hi All,

Attached is my first submission to the Ruby Quiz. I am relatively
new to ruby (7 months) and I have never before been able to solve a
Ruby Quiz 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 Levan
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






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

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
 

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

Forum statistics

Threads
474,262
Messages
2,571,310
Members
47,978
Latest member
SheriBolli

Latest Threads

Top