Last active
August 29, 2015 14:00
-
-
Save stephanwehner/11227766 to your computer and use it in GitHub Desktop.
Ridiculous Adding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
So still faster than a human in most cases.
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
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