I recently began learning Clojure for fun, and after completing the koans, I decide that project Euler would provide my next challenge. Here is the problem statement:
(If someone knows how to put this in spolier tags with out breaking the formatting, please feel free to edit or comment and let me know how to fix it.)
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
- April, June and November.
- All the rest have thirty-one,
- Saving February alone,
- Which has twenty-eight, rain or shine.
- And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
This is the code I used to arrive at the solution. Note that I purposely avoided the date/time APIs so I could try more of the language features out.
(ns euler.n19)
(def week-days (cycle [:mon :tue :wed :thr :fri :sat :sun]))
(defn leap-year?
([year] (if (= 0 (mod year 100))
(= 0 (mod year 400))
(= 0 (mod year 4)))))
(def months [:jan :feb :mar :apr :may :jun :jul :agu :sep :oct :nov :dec])
(def month-length {:jan 31 :feb 28 :mar 31 :apr 30
:may 31 :jun 30 :jul 31 :agu 31
:sep 30 :oct 31 :nov 30 :dec 31})
(def leap-year-month-length (assoc month-length :feb 29))
(def years (->> (range 1901 2001)
(map (fn [yr] (if (leap-year? yr)
leap-year-month-length
month-length)))))
(defn zip
([coll-1 coll-2] map list coll-1 coll-2))
(defn count-number-of-times-day-on-nth-of-month
([day date]
(->> years
(map (fn [month-len] (map #(% month-len) months)))
(flatten)
(reduce (fn [[week-days num-occurrences] curr-month-len]
[(drop curr-month-len week-days)
(if (= day (nth week-days date))
(inc num-occurrences)
num-occurrences)])
[(drop 1 week-days) 0])
(second))))
(defn main ([] println (count-number-of-times-day-on-nth-of-month :sun 0)))
In particular, I'm wondering how the reduce
in count-number-of-times-day-on-nth-of-month
could be clarified since it looks very messy to me.
(As an aside, after a few hours of pouring over this and the koans, I noticed that it is now very hard to type my other code correctly :)