Calendar Calculation in C++


/ Published in: C++
Save to your folder(s)

Brute-force calculation of any date. Includes some very tricky rules for modern-day Gregorian calendar.


Copy this code and paste it in your HTML
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. bool isLeapYear(int year) {
  8. bool retval = false;
  9. if (year % 100 == 0) {
  10. if (year % 400 == 0) {
  11. retval = true;
  12. }
  13. } else if (year % 4 == 0) {
  14. retval = true;
  15. }
  16. return retval;
  17. }
  18.  
  19. int daysInMonth(int month, int year) {
  20. switch (++month) {
  21. case 4:
  22. case 6:
  23. case 9:
  24. case 11:
  25. return 30;
  26. break;
  27. case 2:
  28. if (isLeapYear(year)) {
  29. return 29;
  30. } else return 28;
  31. break;
  32. default:
  33. return 31;
  34. break;
  35. }
  36. }
  37.  
  38. int getFirstDayOfMonth(int month, int year, int day) {
  39. int retval = -1;
  40. int numdays;
  41. if (month == 0) {
  42. numdays = daysInMonth(11, year-1);
  43. } else {
  44. numdays = daysInMonth(month-1, year);
  45. }
  46. int offset = numdays % 7;
  47. if (month == 0 && year == 1900) {
  48. retval = 1;
  49. } else {
  50. retval = (day + offset) % 7;
  51. }
  52.  
  53. return retval;
  54. }
  55.  
  56. int getThirteenth(int firstday) {
  57. return ((13 - firstday) % 7);
  58. }
  59.  
  60. int main() {
  61. ofstream fout ("friday.out");
  62. ifstream fin ("friday.in");
  63.  
  64. int numYears;
  65. fin >> numYears;
  66. int year = 1900;
  67. int firstDay[numYears][12];
  68. int numThirteenths[7];
  69. int day;
  70.  
  71. for (int z = 0; z < 7; ++z) numThirteenths[z] = 0;
  72.  
  73. for (int x = 0; x < numYears; ++x) {
  74. for (int month = 0; month < 12; month++) {
  75. if (year == 1900 && month == 0) {
  76. firstDay[x][month] = 1;
  77.  
  78. } else if (month == 0) {
  79. firstDay[x][month] = getFirstDayOfMonth(month, year, firstDay[x-1][11]);
  80. } else {
  81. firstDay[x][month] = getFirstDayOfMonth(month, year, firstDay[x][month-1]);
  82. }
  83. ++numThirteenths[((firstDay[x][month] + 5) % 7)];
  84. }
  85. ++year;
  86. }
  87.  
  88. fout << numThirteenths[6] << " ";
  89. for (int y = 0; y < 5; ++y) fout << numThirteenths[y] << " ";
  90. fout << numThirteenths[5] << endl;
  91.  
  92. return 0;
  93. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.