Three Minutes of Candy
Autumn Tournament (2023)
Submission name: bonbon.cpp
Problem summary
At each minute, Koko eats one candy for every digit 4 on his four-digit 24-hour clock. He only eats during the daytime interval from 08:00 to 20:00. Given the starting display, examine it and the next two minute displays. Report the last display and the total candies.
Input
One time hh:mm, with two digits for both fields.
Output
The display two minutes later in hh:mm format, then a space and the candy count.
Constraints
00 ≤ hh ≤ 23; 00 ≤ mm ≤ 59.
Worked example
The example is reproduced from the original tournament statement.
Input
14:42
Output
14:44 7
Solution analysis
- Convert the start to minutes since midnight. For offsets 0,1,2, reduce the resulting minute number modulo 1440 to handle a new day.
- During the daytime, split hour and minute into tens and units and count digits equal to four. Keep the time after the third observation and format both fields with two digits.
- The displays 14:42,14:43,14:44 contain respectively 2,2,3 fours, giving 7 candies. Starting at 23:58 instead ends at 00:00 and earns no candies.
Why it works
The loop inspects exactly the three requested displays, including both endpoints. Modulo 1440 gives the correct daily clock time. Each eligible display contributes one candy for each of its four digit positions equal to four, so summing the contributions gives the required total.
Watch out. Include the initial minute. Preserve leading zeros and handle midnight. Nighttime digits do not contribute.
Commented C++17 solution
An independently written complete program with standard headers.
// Key idea: The loop inspects exactly the three requested displays, including both endpoints. Modulo
// 1440 gives the correct daily clock time.
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int hour,minute;
char colon;
cin>>hour>>colon>>minute;
int start=hour*60+minute;
int candies=0;
int current=start;
for(int offset=0;offset<3;offset++){
current=(start+offset)%1440;
hour=current/60;
minute=current%60;
if(current>=8*60&¤t<=20*60){
candies+=hour/10==4;
candies+=hour%10==4;
candies+=minute/10==4;
candies+=minute%10==4;
}
}
cout<<setfill('0')<<setw(2)<<hour<<':';
cout<<setw(2)<<minute<<' '<<candies<<'\n';
}