views:

62

answers:

3

I'm looking for the cleverest algorithm for determining the number of fortnightly occurring events in a given calendar month, within a specific series.

i.e. Given the series is 'Every 2nd Thursday from 7 October 2010' the "events" are falling on (7 Oct 2010, 21 Oct, 4 Nov, 18 Nov, 2 Dec, 16 Dec, 30 Dec, ...)

So what I am after is a function

function(seriesDefinition, month) -> integer 

where:
    - seriesDefinition is some date that is a valid date in the series,
    - month indicates a month and a year

such that it accurately yeilds: numberFortnightlyEventsInSeriesThatFallInCalendarMonth

Examples:

NumberFortnightlyEventsInMonth('7 Oct 2010, 'Oct 2010') -> 2

NumberFortnightlyEventsInMonth('7 Oct 2010, 'Nov2010') -> 2

NumberFortnightlyEventsInMonth('7 Oct 2010, 'Dec 2010') -> 3

Note that October has 2 events, November has 2 events, but December has 3 events.


Psuedocode preferred.

I don't want to rely on lookup tables or web service calls or any other external resources other than potentially universal libraries. For example, I think we can safely assume that most programming languages will have some date manipulation functions available.

A: 

There is no "clever" algorithm when handling dates, there is only the tedious one. That is, you have to specifically list how many days are in each month, handle leap years (every four years, except every 100 years, except every 400 years), etc.

Sjoerd
Your answer is really comment, but thanks for your insightful comment Sjored
Jason Glover
A: 

Well, for the algorithm you are talking about the usual solution is to calculate the day number starting from some fixed date. (Number of day plus cumulated number of days in prev months plus number of years * 365 minus (number of year / 4) plus (number of year / 100) minus (number of year / 400))

Having this, you can easily implement what you need to. You need to calculate which day of week was the 1 January 1. Then you can easily see what is the number of "every second thursdays" from that day to 1 Oct 2010 and 1 Dec 2010. their difference is the value you are looking for.

Vlad
Hmm .... Vlad I think I see where you are going with that, but that looks remarkably like a http://en.wikipedia.org/wiki/Brute-force_search and I was after something a little more elegant. Also, the algorithm is sort of incomplete
Jason Glover
@Jason: it's not a brute force, it's O(1) after all. My answer is just an outline of what can be done. This solution seems to be more elegant, because all the complexity is only on the day number calculation.
Vlad