/extra/project-euler/019/019.factor

http://github.com/abeaumont/factor · Factor · 66 lines · 20 code · 20 blank · 26 comment · 2 complexity · d9f2f94c328ee3aa0daed3c546aefc07 MD5 · raw file

  1. ! Copyright (c) 2007 Samuel Tardieu, Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: calendar combinators kernel math math.ranges namespaces sequences
  4. math.order project-euler.common ;
  5. IN: project-euler.019
  6. ! http://projecteuler.net/index.php?section=problems&id=19
  7. ! DESCRIPTION
  8. ! -----------
  9. ! You are given the following information, but you may prefer to do some
  10. ! research for yourself.
  11. ! * 1 Jan 1900 was a Monday.
  12. ! * Thirty days has September, April, June and November. All the rest have
  13. ! thirty-one, Saving February alone, Which has twenty-eight, rain or
  14. ! shine. And on leap years, twenty-nine.
  15. ! * A leap year occurs on any year evenly divisible by 4, but not on a
  16. ! century unless it is divisible by 400.
  17. ! How many Sundays fell on the first of the month during the twentieth century
  18. ! (1 Jan 1901 to 31 Dec 2000)?
  19. ! SOLUTION
  20. ! --------
  21. ! Use Zeller congruence, which is implemented in the "calendar" module
  22. ! already, as "zeller-congruence ( year month day -- n )" where n is
  23. ! the day of the week (Sunday is 0).
  24. : euler019 ( -- answer )
  25. 1901 2000 [a,b] [
  26. 12 [1,b] [ 1 zeller-congruence ] with map
  27. ] map concat [ 0 = ] count ;
  28. ! [ euler019 ] 100 ave-time
  29. ! 1 ms ave run time - 0.51 SD (100 trials)
  30. ! ALTERNATE SOLUTIONS
  31. ! -------------------
  32. <PRIVATE
  33. : start-date ( -- timestamp )
  34. 1901 1 1 <date> ;
  35. : end-date ( -- timestamp )
  36. 2000 12 31 <date> ;
  37. : first-days ( end-date start-date -- days )
  38. [ 2dup after=? ]
  39. [ dup 1 months time+ swap day-of-week ]
  40. produce 2nip ;
  41. PRIVATE>
  42. : euler019a ( -- answer )
  43. end-date start-date first-days [ 0 = ] count ;
  44. ! [ euler019a ] 100 ave-time
  45. ! 17 ms ave run time - 2.13 SD (100 trials)
  46. SOLUTION: euler019