Clock Walk
Autumn Tournament (2016)
Submission name: chas.cpp
Problem summary
A walk starts at hour t1, minute m1 and ends at hour t2, minute m2. It lasts at least zero minutes and less than one day. One complete lap takes 30 minutes. Find the elapsed minutes and completed laps.
Input
Four integers t1, m1, t2, m2.
Output
Elapsed minutes and number of complete laps, separated by a space.
Constraints
0 ≤ t1,t2 ≤ 23; 0 ≤ m1,m2 ≤ 59.
Worked example
Original statement sample.
Input
23 45 12 34
Output
769 25
Solution analysis
- Convert each time to minutes after midnight: 60·hour+minute. Subtract the start from the finish.
- If the difference is negative, midnight was crossed, so add 1440. An equal start and finish means zero minutes because a full day is excluded. Integer division by 30 counts only completed laps.
- For 23:45 to 12:34 the raw difference is 754−1425=−671. Adding 1440 gives 769 minutes; 769/30 has integer quotient 25.
Why it works
Times repeat every 1440 minutes. Since the true duration belongs to [0,1439], it is the unique representative of the difference modulo 1440 in that interval. Each full lap consumes exactly 30 minutes, so the quotient is exactly the completed-lap count.
Watch out. Do not add a day when the times are equal. Discard a partial final lap.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
using namespace std;
int main(){
int t1,m1,t2,m2;
cin>>t1>>m1>>t2>>m2;
int elapsed=60*t2+m2-60*t1-m1;
if(elapsed<0){
elapsed+=24*60; // The walk crossed midnight.
}
cout<<elapsed<<' '<<elapsed/30<<'\n';
}