Skip to content

Instantly share code, notes, and snippets.

@marcandre
Created August 22, 2012 04:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcandre/3422303 to your computer and use it in GitHub Desktop.
Save marcandre/3422303 to your computer and use it in GitHub Desktop.
Fixx buzz battle
# Hi # Hi
# For this interview, we'd like you to
# Write fizz buzz
# Ok:
def go
fizzy = ->(n){ n % 3 == 0 }
buzzy = ->(n){ n % 5 == 0 }
fizzbuzzy = ->(n){ n % 15 == 0 }
1000.times do |i|
yield case i
when fizzbuzzy then 'fizz buzz'
when fizzy then 'fizz'
when buzzy then 'buzz'
else i
end
end
end
go {|s| puts s}
# Ok. That's one way of doing it. Let's see if you can
# do it differently, without using modulo.
# What do you mean?
# Well, imagine that before your code runs, we do:
class Fixnum; private :%; end
# Easy:
fizzy = ->(n){ n.modulo(3) == 0 }
# Right. Of course, we meant the same for `modulo`
class Fixnum; private :modulo; end
# Ok:
fizzy = ->(n){ n.send(:%,3) == 0 }
# We mean you can't use them!
class Fixnum; undef_method :%, :modulo; end
# Sure...
fizzy = ->(n){ n.divmod(3).last == 0 }
# We mean it. Really.
class Fixnum; undef_method :divmod; end
# How's this?
fizzy = ->(n){ n - (n / 3) * 3 == 0 }
# Oh come on... find a different algorithm.
class Fixnum; undef_method :/, :quo, :div; end
# Not sure what you mean...
fizzy = ->(n){ Rational(n) % 3 == 0 }
# What part of no modulo did you not understand?
# And don't think of using it on BigDecimal either
require 'bigdecimal'
[Rational, BigDecimal, Bignum].each do |k|
k.send :undef_method, :%, :modulo,
:divmod, :/, :quo, :div
end
# I can use a Rational, though:
fizzy = ->(n){ n - Rational(n, 3).to_i * 3 == 0 }
# Are you making fun of us? No Rational for you
Object.send :remove_const, :Rational
Kernel.send :undef_method, :Rational
# There are many other ways to get a rational...
fizzy = ->(n){ n - (0.33333333333333.rationalize * n).to_i * 3 == 0 }
# Grrr, we meant, no Rational
[Float, Integer, Complex].each do |k|
k.send :undef_method, :to_r, :rationalize
end
# Mmmm, can I use to_s?
# to_s? Euh, yeah, otherwise it would be hard to print
# out the numbers...
# Ok, then
fizzy = ->(n){ n.to_s(3)[-1] == '0' }
# Argh. Cheating again.
# Ok, say you can't pass an argument to to_s.
# As you're clearly devious, we have to go through hoops
# to forbid you to do this:
class Fixnum
original = instance_method :to_s
define_method :to_s do
original.bind(self).call
end
end
# So I still have to_s then.
# That's fine:
fizzy = ->(n){ while(n >= 10); n = n.to_s.chars.map(&:to_i).inject(:+); end; [0,3,6,9].include?(n) }
# Ok. No hire. Technical knowledge's good, but
# *no imagination*!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment