Skip to content

Instantly share code, notes, and snippets.

@arieliten
Created July 21, 2010 22:54
Show Gist options
  • Save arieliten/485263 to your computer and use it in GitHub Desktop.
Save arieliten/485263 to your computer and use it in GitHub Desktop.
The Clocks problem (implemented in Ruby)
##########################################################################
# Problem: The Clocks problem
# Description: suppose you have 2 clocks with the following conditions:
# + one clock put forward one minute each hour; and
# + the other clock put back one minute each hour
# Having both clocks showing the same time, the question is:
# + how long we should wait until they show the same time again?
#
# Solution by Ariel Diaz Bermejo
class Clock
attr_accessor :hours, :minutes
def initialize(hours,minutes)
@hours,@minutes = hours,minutes
end
def ==(clock)
(self.hours == clock.hours) && (self.minutes == clock.minutes)
end
def advance(mins)
added_hs = (mins/60)
added_mins = (mins % 60)
mins_remain = 60-self.minutes # Mins remaining until reset minutes
hs_remain = 12-self.hours # Hs remaining until reset hour
added_hs += 1 if added_mins >= mins_remain
# Adding minutes
self.minutes = (added_mins < mins_remain) ? (self.minutes+added_mins) : (added_mins - mins_remain)
# Adding hours
self.hours = (added_hs < hs_remain) ? (self.hours+added_hs) : (added_hs - hs_remain)
end
def to_s
"#{self.hours}:#{self.minutes}"
end
end
# Instantiates 2 clocks with the same time
clock_1 = Clock.new(0,0)
clock_2 = Clock.new(0,0)
puts "We are creating 2 clocks showing the same hour:"
puts "\tClock 1: #{clock_1}"
puts "\tClock 2: #{clock_2}"
puts "Now we're advancing the first clock 61 minutes and the second 59 minutes"
puts "and we wait until they show the same hour again..."
# We're going to advance one clock
1000.times do |i|
clock_1.advance(61)
clock_2.advance(59)
if clock_1 == clock_2
i += 1 # incrementing i because it starts with zero (0) instead of one (1)
puts "Clocks show same hour after #{i/24} days and #{i%24} hours"
puts "\tClock 1: #{clock_1}"
puts "\tClock 2: #{clock_2}"
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment