Return to Snippet

Revision: 61178
at December 2, 2012 12:36 by rtperson


Initial Code
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

bool isLeapYear(int year) {
    bool retval = false;
    if (year % 100 == 0) {
        if (year % 400 == 0) {
            retval = true;
        }
    } else if (year % 4 == 0) {
        retval = true;
    }
    return retval;
}

int daysInMonth(int month, int year) {
    switch (++month) {
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;
            break;
        case 2:
            if (isLeapYear(year)) {
                return 29;
            } else return 28;
            break;
        default:
            return 31;
            break;
    }
}

int getFirstDayOfMonth(int month, int year, int day) {
    int retval = -1;
    int numdays;
    if (month == 0) {
        numdays = daysInMonth(11, year-1);
    } else {
        numdays = daysInMonth(month-1, year);
    }
    int offset = numdays % 7;
    if (month == 0 && year == 1900) {
        retval = 1;
    } else {
        retval = (day + offset) % 7;
    }
    
    return retval;
}

int getThirteenth(int firstday) {
    return ((13 - firstday) % 7);
}

int main() {
    ofstream fout ("friday.out");
    ifstream fin ("friday.in");
    
    int numYears;
    fin >> numYears;
    int year = 1900;
    int firstDay[numYears][12];
    int numThirteenths[7];
    int day;
    
    for (int z = 0; z < 7; ++z) numThirteenths[z] = 0;
    
    for (int x = 0; x < numYears; ++x) {
        for (int month = 0; month < 12; month++) {
            if (year == 1900 && month == 0) {
                firstDay[x][month] = 1;
                
            } else if (month == 0) {
                firstDay[x][month] = getFirstDayOfMonth(month, year, firstDay[x-1][11]);
            } else {
                firstDay[x][month] = getFirstDayOfMonth(month, year, firstDay[x][month-1]);
            }
            ++numThirteenths[((firstDay[x][month] + 5) % 7)];
        }
        ++year;
    }
    
    fout << numThirteenths[6] << " ";
    for (int y = 0; y < 5; ++y) fout << numThirteenths[y] << " ";
    fout << numThirteenths[5] << endl;
    
    return 0;
}

Initial URL

                                

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

Initial Title
Calendar Calculation in C++

Initial Tags

                                

Initial Language
C++