PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/euler19.clj

https://github.com/chrisrisenhoover/Clojure-Euler
Clojure | 97 lines | 70 code | 21 blank | 6 comment | 32 complexity | 097c35f50679e732b9438c3404b5e8a8 MD5 | raw file
  1. (ns clojure-euler.euler19)
  2. ;;How many Sundays where on the first of the month
  3. ;;starting date is WEEKDAY MONTHDAY MONTH YEAR
  4. ;;define this as a DATEVEC
  5. (def days-in-month
  6. {1 31, 2 28, 3 31, 4 30, 5 31, 6 30,
  7. 7 31, 8 31, 9 30, 10 31, 11 30, 12 31})
  8. (defn leap-year?
  9. "test if a year is a leap year"
  10. [year]
  11. (if (zero? (rem year 1000))
  12. (if (zero? (rem year 400))
  13. true
  14. false)
  15. (if (zero? (rem year 4))
  16. true
  17. false)))
  18. (defn end-of-month?
  19. [datevector]
  20. (if (= 2 (datevector 2))
  21. (if (leap-year? (datevector 3))
  22. (if (= (inc (days-in-month (datevector 2))) (datevector 1))
  23. true
  24. false)
  25. (if ( = (days-in-month (datevector 2)) (datevector 1))
  26. true
  27. false))
  28. (if (= (datevector 1) (days-in-month (datevector 2)))
  29. true
  30. false)))
  31. (defn end-of-week?
  32. [datevector]
  33. (if (= 7 (datevector 0))
  34. true
  35. false))
  36. (defn end-of-year?
  37. [datevector]
  38. (if (and (= 12 (datevector 2)) (= 31 (datevector 1)))
  39. true
  40. false))
  41. (defn sunday-first-month?
  42. [datevector]
  43. (if (and (= 7 (datevector 0)) (= 1 (datevector 1)))
  44. (do
  45. (print datevector)
  46. true)
  47. false))
  48. (defn next-day
  49. [datevector]
  50. (let [next-weekday (if (end-of-week? datevector)
  51. 1
  52. (inc (datevector 0)))
  53. next-monthday (if (end-of-month? datevector)
  54. 1
  55. (inc (datevector 1)))
  56. next-month (if (end-of-month? datevector)
  57. (if (end-of-year? datevector)
  58. 1
  59. (inc (datevector 2)))
  60. (datevector 2))
  61. next-year (if (end-of-year? datevector)
  62. (inc (datevector 3))
  63. (datevector 3))]
  64. (vector next-weekday next-monthday next-month next-year)))
  65. (defn euler19
  66. [start-date]
  67. (loop [the-date start-date count 0]
  68. (if (= 2001 (the-date 3))
  69. count
  70. (recur (next-day the-date)
  71. (if (and (sunday-first-month? the-date) (<= 1901 (the-date 3)))
  72. (inc count)
  73. count)))))
  74. ;;(time (euler19 [1 1 1 1900]))
  75. ;;"Elapsed time: 221.860254 msecs"
  76. ;;171