-
-
Save GregMefford/2410325 to your computer and use it in GitHub Desktop.
Berlin Clock Kata
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
# Paul Visscher and Greg Mefford | |
require 'time' | |
class BerlinClock | |
def self.convert_time(time) | |
t = Time.parse(time) | |
clock = "" | |
if t.sec % 2 == 0 | |
clock << "Y\n" | |
else | |
clock << ".\n" | |
end | |
clock << split_lights(t.hour, 4, 4).gsub('*', 'R') | |
clock << split_lights(t.min, 11, 4) | |
clock[14] = "R" if clock[14] == "*" | |
clock[17] = "R" if clock[17] == "*" | |
clock[20] = "R" if clock[20] == "*" | |
clock.gsub!('*', "Y") | |
return clock | |
end | |
private | |
def self.split_lights(value, size1, size2, mod = 5) | |
str = "" | |
fives, ones = value.divmod(mod) | |
str << "*" * fives | |
str << "." * (size1 - fives) | |
str << "\n" | |
str << "*" * ones | |
str << "." * (size2 - ones) | |
str << "\n" | |
end | |
end | |
if defined? RSpec | |
require 'rspec/given' | |
describe BerlinClock do | |
describe "berlin clock" do | |
Then { BerlinClock.convert_time("00:00:00").should == "Y\n....\n....\n...........\n....\n" } | |
Then { BerlinClock.convert_time("00:00:01").should == ".\n....\n....\n...........\n....\n" } | |
Then { BerlinClock.convert_time("00:00:02").should == "Y\n....\n....\n...........\n....\n" } | |
Then { BerlinClock.convert_time("01:00:02").should == "Y\n....\nR...\n...........\n....\n" } | |
Then { BerlinClock.convert_time("02:00:02").should == "Y\n....\nRR..\n...........\n....\n" } | |
Then { BerlinClock.convert_time("03:00:02").should == "Y\n....\nRRR.\n...........\n....\n" } | |
Then { BerlinClock.convert_time("04:00:02").should == "Y\n....\nRRRR\n...........\n....\n" } | |
Then { BerlinClock.convert_time("05:00:02").should == "Y\nR...\n....\n...........\n....\n" } | |
Then { BerlinClock.convert_time("06:00:02").should == "Y\nR...\nR...\n...........\n....\n" } | |
Then { BerlinClock.convert_time("06:01:02").should == "Y\nR...\nR...\n...........\nY...\n" } | |
Then { BerlinClock.convert_time("06:27:02").should == "Y\nR...\nR...\nYYRYY......\nYY..\n" } | |
Then { BerlinClock.convert_time("06:59:59").should == ".\nR...\nR...\nYYRYYRYYRYY\nYYYY\n" } | |
Then { BerlinClock.convert_time("23:00:00").should == "Y\nRRRR\nRRR.\n...........\n....\n" } | |
Then { BerlinClock.convert_time("23:59:59").should == ".\nRRRR\nRRR.\nYYRYYRYYRYY\nYYYY\n" } | |
end | |
end | |
else | |
# if not running in rspec... | |
while true do | |
puts BerlinClock.convert_time(Time.now.to_s).gsub(".", "\e[1m\e[30m.\e[0m").gsub("Y", "\e[1m\e[33mY\e[0m").gsub("R", "\e[1m\e[31mR\e[0m") | |
puts Time.now | |
sleep 1 | |
puts "\e[7A" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment