Programming Praxis posted about calculating clock angles, specifically to:
Write a program that, given a time as hours and minutes (using a 12-hour clock), calculates the angle between the two hands. For instance, at 2:00 the angle is 60°.
Wikipedia has a page about clock angle problems that we can pull a few test cases from:
{ 0 } [ "12:00" clock-angle ] unit-test { 60 } [ "2:00" clock-angle ] unit-test { 180 } [ "6:00" clock-angle ] unit-test { 18 } [ "5:24" clock-angle ] unit-test { 50 } [ "2:20" clock-angle ] unit-test
The hour hand moves 360° in 12 hours and depends on the number of hours and minutes (properly handling midnight and noon to be 0°
):
:: hour° ( hour minutes -- degrees ) hour [ 12 = 0 ] keep ? minutes 60 / + 360/12 * ;
The minute hand moves 360° in 60 minutes:
: minute° ( minutes -- degrees ) 360/60 * ;
Using these words, we can calculate the clock angle from a time string:
: clock-angle ( string -- degrees ) ":" split1 [ number>string ] bi@ [ hour° ] [ minute° ] bi - abs ;
1 comment:
Hi,
the [ 12 = 0 ] keep ? can be replaced with 12 mod
and maybe
360/60 * to 6 *
I understand that 360/60 will be dealt with factor, but reading the code IMHO will differ. the first reads like 360 degrees by 60 minutes * minutes, the later reads 6 degree for each minute (kind of 1 level ahead in comprehension - this is negligible here but may adds up in bigger program)
Thanks for the website and the link
Post a Comment