Other
than use brute force method to loop through the month to count days, it can be
calculated as below (in Java Script):
Math.floor((dayInMonth - ((w - weekdayOfDay1 + 7) % 7) + 6)
/ 7)
Where dayInMonth is the number of days in that month, w is
the day of week (e.g. Sunday) we want to count and the weekdayOfDay1 is the day
of week on the first day of that month.
Notes, all "day of week" are mapped as 1 for Monday, 2 for Tuesday…, 7 for
Sunday.
As the set of results for is limited, pre-calculated values
can be used and simple arrays or mappings can be loaded in programs to get the
result directly as an alternative method.
The mapping table is pretty small (196 entries):
7 (possible day of week to be counted) X 7 (possible day of week on the first day of the month) X 4 (possible number of days
in a month) .
e.g. table for first day of the month is Monday:
e.g. table for first day of the month is Monday:
| wday\nday | 28 | 29 | 30 | 31 |
| 1 | 4 | 5 | 5 | 5 |
| 2 | 4 | 4 | 5 | 5 |
| 3 | 4 | 4 | 4 | 5 |
| 4 | 4 | 4 | 4 | 4 |
| 5 | 4 | 4 | 4 | 4 |
| 6 | 4 | 4 | 4 | 4 |
| 7 | 4 | 4 | 4 | 4 |
Not sure about the performance differences.
BL
No comments:
Post a Comment