Ruby解24点

今天培训python,讲课老师无意间提及他用python解24点用了48行代码,心中默念:challenge accepted!于是写了一个ruby版本,用了26行~


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, 8, 9, 5, 9
puts ret


其实有点耍赖皮,因为ruby中加减乘除不是关键字,是方法,所以能省掉很多代码,而且有的能写成一句太长我也自觉分成三行了。不过想想python也省掉很多end,大家都耍赖皮,就无所谓了,哈哈。
ruby数组操作实在太牛逼了,我相信一定有更变态更短的方法存在,欢迎大家po代码比较!

提供一个测试连接:http://app.baidu.com/app/enter?appid=123723
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值