ruby
#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
Remarks:
- Start it with
ruby program-my-microwave-oven.rb
and a unit test is evaluated.
- Start it with
ruby program-my-microwave-oven.rb 10:00
and it writes 960S
Some remarks on the rules (and my interpretation):
- The shortest for
10:00
is 960S
(9 minutes and 60 seconds -> 10 minutes).
- The shortest for
10:39
is 999S
(9 minutes and 99 seconds -> 10 minutes and 39 seconds).
- for
4:00
it prefers ++++
(less finger movements)
400S
or++++
? \$\endgroup\$++++
wins. :) \$\endgroup\$888S
shorter than928S
, but900S
shorter than860S
? i'm gonna need precise geometry of your buttons and each of their positions. \$\endgroup\$