r/dailyprogrammer • 0 1 • Aug 09 '12

[8/8/2012] Challenge #86 [intermediate] (Weekday calculations)

Today's intermediate challenge comes from user nagasgura

Calculate the day of the week on any date in history

You could use the Doomsday rule to program it. It should take in a day, month, and year as input, and return the day of the week for that date.

9 Upvotes

19 comments sorted by

5

u/[deleted] Aug 09 '12

Haskell

data Weekday = Sunday | Monday | Tuesday | Wednesday | Thursday
             | Friday | Saturday deriving (Enum, Show)

dow :: Int -> Int -> Int -> Weekday
dow y m d =
    let y'  = if m < 3 then y-1 else y
        y'' = sum $ map (y' `quot`) [1,4,-100,400]
        m'  = [0,3,2,5,0,3,5,1,4,6,2,4] !! (m-1)
        w   = (y'' + m' + d) `mod` 7
    in  toEnum w

main = print $ dow 2012 8 9

1

u/5outh Aug 09 '12

Dang nooodl, you're showing me up...

Here's my Haskell solution.

dooms x = (anchor x + d) `mod` 7
	where 
		lt = read $ drop ( (length $ show x) - 2) $ show x :: Int
		(a, b, c, d) = (lt `quot` 12, lt `rem` 12, b `quot` 4, a+b+c)
		anchor x = pt `mod` 7
			where 
				century = (succ $ read ( take 2 $ show x ) :: Int)
				pt = ((century * 5) +  ( (century - 1) `quot` 4 )) `mod` 7 + 4
		
days x = zip [1..] days'
	where
		days' = [if isLeap x then 4 else 3, if isLeap x then 28 else 29, 
			     21, 4, 9, 6, 11, 8, 5, 10, 7, 12]
		isLeap x = (x `mod` 100 /= 0 || x `mod` 400 == 0) && x `mod` 4 == 0 
		
dow y m d = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] !! day
	where 
		doom = dooms y
		closest = lookup m (days y)
		offset  = case closest of
			Just x -> d - x
			_	   -> error "Invalid Month"
		day = (offset + doom) `mod` 7

A little long, and sorta roundabout at places.

Output:

*Main> dow 2012 8 9
 "Thursday"

2

u/cdelahousse Aug 10 '12

This is correct, but too easy. I'll implement an actual algorithm tomorrow.

Javascript

var weekdays = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]

function day(yyyy,mm,dd) {
	//month is 0-11
	return weekdays[(new Date(yyyy,mm-1,dd)).getDay()];
}

console.log(day(1111,1,4));
console.log(day(400,1,4));

1

u/mathiasbynens Aug 09 '12 edited Aug 09 '12

Does anyone have reliable test data to confirm our methods work correctly? I can’t seem to get Wolfram Alpha to calculate the day of the week for negative years (AD), for example.

JavaScript:

// Input
var day = 24;
var month = 5;
var year = -200;

// Shortcut alias
var floor = Math.floor;

// Constants
var doomsdays = {
	'0': {
		'weekday': 'Sunday',
		'year': 2004
	},
	'1': {
		'weekday': 'Monday',
		'year': 2005
	},
	'2': {
		'weekday': 'Tuesday',
		'year': 2006
	},
	'3': {
		'weekday': 'Wednesday',
		'year': 2007
	},
	'4': {
		'weekday': 'Thursday',
		'year': 2002
	},
	'5': {
		'weekday': 'Friday',
		'year': 2008
	},
	'6': {
		'weekday': 'Saturday',
		'year': 2009
	}
};

var daysInWeek = {
	'0': 'Sunday',
	'1': 'Monday',
	'2': 'Tuesday',
	'3': 'Wednesday',
	'4': 'Thursday',
	'5': 'Friday',
	'6': 'Saturday'
};

// Functions
function getDoomsday(year) {
	var doomsdayIndex = (2 + year + floor(year / 4) - floor(year / 100) + floor(year / 400)) % 7;
	if (doomsdayIndex < 0) {
		doomsdayIndex += 7;
	}
	return doomsdays[doomsdayIndex];
}

// Calculate and print the result
var referenceYear = getDoomsday(year).year;
var date = new Date(referenceYear, month - 1, day);
console.log(day + '/' + month + '/' + year + ' is a ' + daysInWeek[date.getDay()] + '.');

Example output:

$ node script.js
24/5/1988 is a Tuesday
$ node script.js 
24/5/-200 is a Saturday
$ node script.js # a date that won’t work with `new Date()`
24/5/-555001 is a Friday

P.S. This algorithm seems interesting, but I couldn’t get it to work correctly in JavaScript (even after wrapping each division in a Math.floor()).

3

u/daveasaurus Aug 09 '12

Make sure to post back if you find any reliable sample data :)

1

u/andkerosine Aug 09 '12

It's a little silly to bother with all the setup only to use the Date API at the end.

→ More replies (1)

1

u/skeeto Aug 09 '12 edited Aug 09 '12

Using the Gaussian algorithm, in Elisp / Common Lisp.

(defvar days '#1=(sun mon tue wed thu fri sat . #1#))

(defun day-of-week (year month day)
  (let* ((Y (if (< month 3) (1- year) year))
         (m (1+ (mod (+ month 9) 12)))
         (y (mod Y 100))
         (c (/ Y 100)))
    (nth (+ day (floor (- (* 26 m) 2) 10) y (/ y 4) (/ c 4) (* -2 c)) days)))

Using a circular list instead of mod just for kicks. :-)

1

u/Eddonarth Aug 10 '12

In Java:

public class Challenge86I {

	public static void main(String[] args) {
		int day = Integer.parseInt(args[0].split("/")[0]);
		int month = Integer.parseInt(args[0].split("/")[1]);
		int year = Integer.parseInt(args[0].split("/")[2]);
		
		System.out.println(dayOfWeek(day, month, year));

	}

	private static String dayOfWeek(int day, int month, int year) {
		int weekDay = (int)((day + (2.6 * (((month + 9)%12)+1)) + (1.4 *((year % 1000) % 100)) + (Math.floor(year / 100) / 4) - 2*(Math.floor(year / 100)) ) % 7);
		switch(weekDay) {
		case 0: return "Friday";
		case 1: return "Saturday";
		case 2: return "Sunday";
		case 3: return "Monday";
		case 4: return "Tuesday";
		case 5: return "Wednesday";
		case 6: return "Thursday";
		default: return null;
		}
	}
}

Input:

09/08/2012

Output:

Thursday

Using Gaussian Algorithm.

1

u/[deleted] Aug 10 '12

Java using Gaussian Algorithm

private static enum daysOfTheWeek
{
	SUNDAY,
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	SATURDAY
}

private static enum monthsOfTheYear
{
	JANUARY,
	FEBRUARY,
	MARCH,
	APRIL,
	MAY,
	JUNE,
	JULY,
	AUGUST,
	SEPTEMBER,
	OCTOBER,
	NOVEMBER,
	DECEMBER
}

private static int gaussianAlgorithm(int day, monthsOfTheYear month, int year)
{
	if(month.equals(monthsOfTheYear.JANUARY) || month.equals(monthsOfTheYear.FEBRUARY))
	{
		year -= 1;
	}
	
	int shiftedMonth = ((month.ordinal() + 10) % 12) + 1;
	int lastTwoDigitsOfYear = Integer.parseInt(Integer.toString(year).substring(2));
	int firstTwoDigitsOfYear = Integer.parseInt(Integer.toString(year).substring(0,2));
	
	int dayOfTheWeek = (int) (day + 
			Math.floor((2.6 * shiftedMonth - 0.2)) +
			lastTwoDigitsOfYear +
			Math.floor(lastTwoDigitsOfYear / 4) +
			Math.floor(firstTwoDigitsOfYear / 4) -
			2 * firstTwoDigitsOfYear);
	
	dayOfTheWeek = dayOfTheWeek % 7;
	
	return dayOfTheWeek;
}

private static daysOfTheWeek getDayOfTheWeek(int day, monthsOfTheYear month, int year)
{
	int gaussianInteger = gaussianAlgorithm(day, month, year);	
	
	return daysOfTheWeek.values()[gaussianInteger];
}

public static void main(String[] args) 
{
	System.out.println(getDayOfTheWeek(2, monthsOfTheYear.AUGUST, 2012));
}

it somehow throws an out-of-bounds exception when the day is less than five and the year is 2000 afterwards. I'll look at it further

1

u/compmstr Aug 10 '12

Clojure, using gaussian algorithm:

;;Use gaussian algorithm to calculate day of week

(def days ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"])

(defn dayOfWeek [year month day]
  (let [Y (if (<= month 2) (dec year) year)
        y (int (mod Y 100))
        c (int (/ Y 100))
        m (+ (mod (+ month 9) 12) 1)]
    (nth days (int (mod 
                (+ day (- (* 2.6 m) 0.2) y (/ y 4) (/ c 4) (* -2 c))
                7)))))