PHP Job Interview Task: Day of Week Calculation

Not so long ago, I was given a job interview task. I was to write a function which deduces the day of the standard 7-day week of an imaginary calendar, provided I know how often leap years happen, if at all, how many months their year has, and how many days each month has.

This is a fairly common introductory job-interview task, and in this article I'll be solving and explaining the math behind it. I'm no Rainman so feel free to throw simplifications and corrections at me – I'm sure my way is one of the needlessly complex ones. This article will be presenting two ways of approaching the problem – one that allows you to mentally do this on-the-fly (impress your friends, I guess?), and one that is more computer friendly (fewer lines of code, larger numbers).

Given that the first day of the year 1900 was Monday, write a function that will print the day of the week for a given date. Example, for input {day: 17, month: 11, year: 2013} the output is "Saturday".

Throughout the rest of the article, I will be using the following date format: dd.mm.yyyy, because it's what makes sense.

Preparation

Before starting out on any brainy venture, it's important to have a proper environment set up in order to avoid wasting time on things that could have been prepared in advance. I always recommend you venture into coding job interview tasks with a revved up development environment, ready to test your code at a moment's notice.

Create a new folder containing two subfolders: classes, and public. Yes, this is a throwaway task that can be solved in a simple procedural function, but I like to be thorough. You'll see why.

In the classes subfolder, create an empty PHP class called CalendarCalc.php. In the public subfolder, create a file called index.php with the following content:

<?php
require_once '../classes/CalendarCalc.php';
echo "Hello";

If you can open this in your browser and "Hello" is displayed, you're ready to get started.

CalendarCalc initialization

To make things easier to verify and visualize, I've created a demo method which prints out the entire calendar from 1.1.1900. to 22.13.2013. This will allow us to easily check if our calculation function works. First, though, initialize the class like so:

$aDays is an array of days. Defining it made sure each day of the week has a numeric index assigned to it – something of utmost importance when determining the day of the week later on. We cache its length with the $iNumDays property. This allows us to expand the days array later on, if we so choose – another task might ask for the same calculation, but might mention that the week has more or less than 7 days.

$iStartDayIndex is the index of Monday (in this case), because the start day (1.1.1900.) is defined as Monday in the task description. When we have the index of the start day, we can use it in tandem with a calculated offset to get the real day of the week. You'll understand what I mean in a bit.

$aInput is an array to hold the input values. When we instantiate the CalendarCalc, we pass in the date values for which we want to know the day of the week. This property stores those values, making them available for every alternative calc method we think up, thus making sure we don't need to forward them along, or even worse, repeat them in another function call. The logic of $aInput, $iStartDayIndex and $iNumDays is in the __construct method.

Don't bother trying to understand this method – it's entirely unimportant. It's only there to help us verify our work, and is in fact partially based on the second solution we'll be presenting in this article.

…and open it in the browser. You should see a calendar output not unlike the one in the image below:

We now have a way to check the results against the truth (notice that the date 17.11.2013. is indeed Saturday).

The mental way

The mental way to do this calculation is actually quite simple. First, we need the number of leap years between the base date, and our given date. 1900 is divisible by 5 and is itself a leap year. The number of leaps is thus the difference in years between the input date and the base date, divided by 5, rounded down (only fully elapsed years count, naturally), plus one for 1900. Create a new method in CalendarCalc called calcFuture and give it this content:

The total number of days in their year is, thus, 280, or 279 on leap years. If we take the modulo of 280 % 7, we get 0, because 280 is divisible by 7. On leap years, the modulo is 6.

This means that every year of that calendar begins on the same day, except on leap years, when it begins on the day that precedes the previous year's first day. Thus, if 1.1.1900. was Monday:

1.1.1901. is Monday

1.1.1902. is Sunday

1.1.1903. is Sunday

1.1.1904. is Sunday

1.1.1905. is Saturday

1.1.1906. is Saturday

etc…

According to this, we can calculate the number of day moves until our input year. Seeing as we know we have 23 leaps until the input date (2013), we moved back a day 23 times. The modulo of 23 % 7 is 2, meaning we came full circle 3 times and then two more days (this is the offset) – 1.1.2013. was Saturday. Check on the demo calendar and see for yourself.

Let's put this into code. After the "leaps" line above, add the following:

First, we calculate the offset. Then, we calculate the new index of the days array, which varies depending on whether or not the new index is positive. This gives us the day of the week on which our input year starts.

We also know that each month X with 21 days makes the next month Y start on the same day as month X did, because 21 % 7 = 0. During odd months, however, the starting day moves ahead by one (22 % 7 = 1). So if Month 1 started with Saturday, Month 2 starts with Sunday, Month 3 with Sunday, Month 4 with Monday, and so on. We conclude that every odd month that passed since the start of the year until our input date's month has advanced the day index by 1. We're in month 11, so there were 5 odd months. The new offset is +5 or in our case, the 11th month of 2013 begins on Thursday. Let's put it into code immediately under the previous lines.

The machine-friendly way

A perhaps simpler approach is just calculating the number of days that have elapsed since the base date, modulo that by 7 and get the offset that way. There's not many people who can calculate numbers of this magnitude on the fly, though, and that's why it's more machine-friendly.

Conclusion

To see a live example of this calculation, please check here. You can browse the containing directory at that URL to see the files, or you can download the complete source code of that demo site, along with the final CalendarCalc class, from Github. The repo/demo has slightly more code than presented in this article – some html5boilerplate was used to make it more organized and to enable ajax requests to check the dates as you enter them, so you don't need to reload the screen and regenerate the calendar every time you check for a date.

If you have alternative solutions or suggestions for improvement, please leave them in the comments below – like I said I'm no math wiz and I welcome the opportunity to learn more. For example, one should take corner cases into account – edge dates, or dates in the past require more modifications to the original algorithm. I'll leave that up to you. Feel free to submit a pull request and you'll get a shout out in the article!

Hope you enjoyed this and learned something new! Good luck in your interviews!

Bruno is a blockchain developer and code auditor from Croatia with Master’s Degrees in Computer Science and English Language and Literature. He's been a web developer for 10 years until JavaScript drove him away. He now runs a cryptocurrency business at Bitfalls.com via which he makes blockchain tech approachable to the masses, and runs Coinvendor, an on-boarding platform for people to easily buy cryptocurrency. He’s also a developer evangelist for Diffbot.com, a San Francisco-based AI-powered machine vision web scraper. Read more about his background with the blockchain here.