Friday, the Thirteenth

March 13, 2009

We reuse the julian date function from the Mardi Gras exercise:

(define (julian year month day)
  (let* ((a (quotient (- 14 month) 12))
         (y (+ year 4800 (- a)))
         (m (+ month (* 12 a) -3)))
    (+ day
       (quotient (+ (* 153 m) 2) 5)
       (* 365 y)
       (quotient y 4)
       (- (quotient y 100))
       (quotient y 400)
       (- 32045))))

Then we check each Friday for the next 120 months:

(define (fri13-ten year month)
  (let loop ((m (if (= month 12) 1 (+ month 1)))
             (y (if (= month 12) (+ year 1) year))
             (n 0) (k 120))
    (if (zero? k) n
      (loop (if (= m 12) 1 (+ m 1))
            (if (= m 12) (+ y 1) y)
            (if (= (modulo (julian y m 13) 7) 4) (+ n 1) n)
            (- k 1)))))

There are seventeen Fridays the thirteenth in the next ten years:

> (fri13-ten 2009 3)
17

The seventeen Fridays are 11/2009, 8/2010, 5/2011, 1/2012, 4/2012, 7/2012, 9/2013, 12/2013, 6/2014, 2/2015, 3/2015, 11/2015, 5/2016, 1/2017, 10/2017, 4/2018, and 7/2018. You can run the code at http://programmingpraxis.codepad.org/RqYg0Qfi.

Pages: 1 2

4 Responses to “Friday, the Thirteenth”

  1. JLR said

    Approximately 120/7 = 17

  2. etiene said

    I can’t see the exemple

  3. programmingpraxis said

    @etiene: Welcome to Programming Praxis! Click on Page 2 at the end of the exercise.

Leave a comment