Skip to content

Instantly share code, notes, and snippets.

@stephanwehner
Last active August 29, 2015 14:00
Show Gist options
  • Save stephanwehner/11227766 to your computer and use it in GitHub Desktop.
Save stephanwehner/11227766 to your computer and use it in GitHub Desktop.
Ridiculous Adding
# Add two numbers in Ruby.
# Strategy: make a list of known sums, and look up the one in question.
# What's the point? The point is: nowadays computing machinery is so powerful that
# implementation in many cases doesn't matter. The most ridiculous approach can still be
# useful, and improving it, a waste of time.
# So here's a very silly way how to add numbers.
def add_by_grep(a,b)
sums = []
1000.times do |x|
1000.times do |y|
sums << "#{x}+#{y}=#{x+y}"
end
end
matches = sums.grep /\A#{a}\+#{b}=\d+\Z/
case matches.size
when 0
raise "Don't know"
when 1
matches.first =~ /\A#{a}\+#{b}=(\d+)\Z/
return $1.to_i
else
raise "Unexpected error. More than one match! #{matches.inspect}"
end
end
@stephanwehner
Copy link
Author

Sample usage:

$ irb
1.9.3p392 :033 > require '/tmp/ridiculous_adding.rb'
=> true
1.9.3p392 :034 > s = Time.new; puts add_by_grep(12,99); puts "Took #{Time.new - s} seconds"
111
Took 1.313211 seconds

@stephanwehner
Copy link
Author

So still faster than a human in most cases.

@stephanwehner
Copy link
Author

Caching does improve the timing though. I'm getting it down to 0.4 secs, when reusing the "sums" array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment