今天
培训python,讲课老师无意间提及他用python解24点用了48行代码,心中默念:challenge accepted!于是写了一个ruby
版本,用了26行~
class="ruby" name="code">
def calculator number, *factors
if factors.size == 1
if number.to_f == factors[0].to_f
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 == :- or operator == :/
temp_nmuber = factor.send(operator[0], number.to_f)
if !calculator(temp_nmuber, * temp_factors).nil?
return "(#{factor} #{operator[1]} #{calculator(temp_nmuber, * temp_factors)})"
end
end
end
end
end
nil
end
#ret = calculator 3, 1, 2
ret = calculator 24, 8, 9, 5, 9
puts ret
其实有点耍赖皮,因为ruby中加减乘除不是
关键字,是方法,所以能省掉很多代码,而且有的能写成一句太长我也自觉分成三行了。不过想想python也省掉很多end,大家都耍赖皮,就无所谓了,哈哈。
ruby数组操作实在太牛逼了,我相信一定有更变态更短的方法存在,欢迎大家po代码比较!
提供一个测试连接:http://app.baidu.com/app/enter?appid=123723