Created
March 4, 2014 07:55
-
-
Save piecehealth/9342052 to your computer and use it in GitHub Desktop.
解24点
This file contains 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
def calculator number, *factors | |
if factors.size == 1 | |
if number.to_f.round(10) == factors[0].to_f.round(10) | |
return factors[0].to_s | |
else | |
return nil # nil stand for no solution | |
end | |
else | |
factors.each_with_index do |factor, idx| | |
[[:+, :-], [:-, :+], [:*, :/], [:/, :*]].each do |operator| | |
temp_nmuber = number.send(operator[0], factor.to_f) | |
temp_factors = factors.clone | |
temp_factors.delete_at(idx) | |
return "(#{calculator(temp_nmuber, * temp_factors)} #{operator[1]} #{factor})" if !calculator(temp_nmuber, *temp_factors).nil? | |
if operator[0] == :- or operator[0] == :/ | |
temp_nmuber = factor.send(operator[0], number.to_f) | |
if !calculator(temp_nmuber, * temp_factors).nil? | |
return "(#{factor} #{operator[0]} #{calculator(temp_nmuber, * temp_factors)})" | |
end | |
end | |
end | |
end | |
end | |
nil | |
end | |
#ret = calculator 3, 1, 2 | |
ret = calculator 24, 3,3,8,8 | |
#ret = calculator 24, 5,5,5,1 | |
#ret = calculator 4.8, 5,5,1 | |
puts ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment