The question is basically like this: Given year, month, day and duration, calculate the future date based on given data and duration. The given date guarantees to be after 1900-01-01, and the duration k is between [0, 10000].
For example: Input: 2016 10 1 100(meaning given 2016-10-1, what is the future date after 100 days) Output: 2017-01-09
Another example: Input: 2017 1 1 10 Output: 2017-01-11
I have done my solution, but it is trivial and ugly. The most frustrating part is line 44 - 47, where I have to handle special cases on month and year. I feel like this special and trivial handling is due to my design of calculating month, but I cannot figure out a more universal/clear solution except for current solution.
Love to hear your advice! Thank you!
Code with line indication and better format fyi : https://paste.ubuntu.com/24765263/
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std; // I know global namespace is bad practice. Just to save time.
int getMonthDays(int y, int m){
unordered_map <int, int >daysMap = {{1,31}, {2,28}, {3,31}, {4,30}, {5,31}, {6,30}, {7,31}, {8,31}, {9,30}, {10,31}, {11,30}, {0,31}};
if (m == 2){
if (y % 400 ==0 || (y % 100 != 0&& y % 4 == 0)){
return 29;
}
else{
return 28;
}
}
else{
return daysMap[m];
}
}
int main (){
int year, month, day, duration;
cin >> year >> month >> day >> duration;
int res_year;
string res_month, res_day;
int days = getMonthDays(year, month) - day;
while ( days < duration ){
month++;
if(days + getMonthDays(year + month/12, (month - 12 * (month/13))% 12) > duration){
break;
}
else{
days += getMonthDays(year + month/12, (month - 12 * (month/13))% 12);
}
}
res_year = year + month / 12 ;
res_month = (month - 12 * (month/13))% 12 >= 10 ? to_string((month - 12 * (month/13))% 12) : "0" + to_string((month - 12 * (month/13))% 12);
if (res_month == "00"){
res_month = "12"; // dont have set month "12", so if get month as "00", convert it to "12"
res_year -= 1; // if the result month is "12", year minus 1 coz Month December is still in this year.
}
if (duration - days > 0 ){
if (duration - days >= 10){
res_day = to_string(duration - days);
}
else{
res_day = "0" + to_string(duration - days);
}
}
else{
res_day = to_string(day + duration);
}
cout << res_year << "-" << res_month << "-" << res_day;
}
std::chrono::xxx_clock::now()
. It might be worth updating the answer you've given long ago if you think the approach is good. \$\endgroup\$