• 0

Interesting algorithm


Question

So, I came accross this code to calculate which day of the week a date is on, the source is here: http://www.daniweb.com/code/snippet65.html#

//
// given month, day, year, returns day of week, eg. Monday = 0 etc.
// tested for 1901 to 2099 (seems to work from 1800 on too)
// 
int weekday(int month, int day, int year)
{	
  int ix, tx, vx;

  switch (month) {
	case 2  :
	case 6  : vx = 0; break;
	case 8  : vx = 4; break;
	case 10 : vx = 8; break;
	case 9  :
	case 12 : vx = 12; break;
	case 3  :
	case 11 : vx = 16; break;
	case 1  :
	case 5  : vx = 20; break;
	case 4  :
	case 7  : vx = 24; break;
  }
  if (year > 1900)  // 1900 was not a leap year
	year -= 1900;
  ix = ((year - 21) % 28) + vx + (month > 2);  // take care of February 
  tx = (ix + (ix / 4)) % 7 + day;			  // take care of leap year
  return (tx % 7);
}

Now, I can obviously read what the code is doing, however I have no idea WHY it works. Any ideas?

On a completely unrelated thing, you can remove the

if (year > 1900)  // 1900 was not a leap year
	year -= 1900;

and change?

return (tx % 7);

to

return ((tx + 5) % 7);

and it works the same, I prefer this other solution to the one on the webpage.

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

I won't pretend to understand the function, but it really doesn't work since it is wrong for several periods after 2/28/2100 and several periods prior to 1901. I can imagine several applications for which this would be simply unacceptable.

A more accurate and reliable way would be to calculate the number of days between the date and a reference date (with a known weekday), and simply mod 7 the difference.

Link to comment
Share on other sites

  • 0

@boogerjones,

- That's exactly what the above algorithm is doing. It's just calculating the number of days between the given date and a base date then mod 7. The actual problem is to find a base date without having to hardcode it. Mathematician J.H Conway proposed the Doomsday rule as it can be applied for any date, you'll just have to expand your algorithm a little to treat the cases of all 4 "anchor" century days (more details on Wikipedia & co).

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.