我很懒,所以我总是用最少的按钮来编程我的微波炉。我的微波炉有以下按钮:
+0**.**9S我的食品包装指定了MM:SS的时间,所以程序必须接受这个输入。
+ (记住“分钟加”意味着开始)61S (秒数可以超过59秒,但是“分钟+”不能与数字一起工作-我认为这是我的微波炉中的一个设计缺陷)900S (比+++++++++短)发布于 2012-10-24 01:41:26
var x = /(\d+):(\d\d)/.exec('<time here>');
x[1] === '0' ? +x[2] + 'S' :
x[1] < 4 && x[2] === '00' ? (
x[1] === '1' ? '+' :
x[1] === '2' ? '++' : '+++') :
x[2] < 40 ?
(x[1] - 1 ? x[1] - 1 : '') + '' + (6 + +x[2][0]) + x[2][1] + 'S' :
x[1] + x[2] + 'S'发布于 2012-10-24 21:11:34
#Build a string for the microwave
def build_result(minutes, seconds)
duration = minutes * 60 + seconds
if duration < 99
result = "%iS" % [ duration] #shortcut '90S' instead '130S'
else
result = "%i%02iS" % [ minutes, seconds]
end
result
end
#Call microwave optimizer
def microwave( input )
minutes = input.split(/:/).first.to_i
seconds = input.split(/:/).last.to_i
#build result
result = build_result(minutes, seconds)
#try a shorter result, make 999S out of '10:39':
if seconds < 40 and minutes > 0
result2 = build_result(minutes - 1, seconds + 60) #try a
result = ( result.size <= result2.size ? result : result2 )
end
#Check if a version with only '+' is shorter
if seconds == 0 and minutes <= result.size
result = '+' * minutes
end
result
end
#Test if called with an argument
if ARGV.empty?
require 'test/unit' #Exceute a test
class MicrowaveTest < Test::Unit::TestCase
def test_007
assert_equal('7S', microwave('0:07'))
end
def test_100
assert_equal('+', microwave('1:00'))
end
def test_101
assert_equal('61S', microwave('1:01'))
end
def test_130
assert_equal('90S', microwave('1:30'))
end
def test_400
#~ assert_equal('400S', microwave('4:00'))
assert_equal('++++', microwave('4:00'))
end
def test_500
assert_equal('500S', microwave('5:00'))
end
def test_900
assert_equal('900S', microwave('9:00'))
end
def test_1000
#~ assert_equal('1000S', microwave('10:00'))
assert_equal('960S', microwave('10:00'))
end
def test_1015
#~ assert_equal('1015S', microwave('10:15'))
assert_equal('975S', microwave('10:15'))
end
def test_1039
#~ assert_equal('1039S', microwave('10:39'))
assert_equal('999S', microwave('10:39'))
end
end
else #started via shell, evaluate input
puts microwave(ARGV.first)
end备注:
ruby program-my-microwave-oven.rb启动它,并对单元测试进行评估。ruby program-my-microwave-oven.rb 10:00启动它,然后编写960S关于规则的几点意见(以及我的解释):
10:00的最短时间是960S (9分60秒-> 10分钟)。10:39的最短时间是999S (9分99秒-> 10分39秒)。4:00来说,它更喜欢++++ (少动手指)https://codegolf.stackexchange.com/questions/8791
复制相似问题