klenwell information services : Euler19Ruby

Project Euler #19

return to Project Euler

http://projecteuler.net/problem=19

=begin

    http://projecteuler.net/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)?
   
   
    PERFORMANCE
    real    0m5.630s

=end

require 'date'

#
# Constants / Globals
#
SUNDAY = 0
MONDAY = 1
JANUARY = 1

def assert_match(value, expected)
    raise "value %s != expected %s" % [value, expected] unless value == expected
    true
end


#
# Test Case / Solution
#
def test_case
    day1_1900 = Date.new(1900, 1, 1)    
    assert_match(day1_1900.wday, MONDAY)
    assert_match((day1_1900 + 1).wday, MONDAY + 1)
    puts "test case passed!"
end


def solution
    return count_first_of_month_sundays("1901-01-01", "2000-12-31")
end



#
# Support Code
#
def count_first_of_month_sundays(start_date_str, end_date_str)
    count = 0
    start_date = Date.strptime(start_date_str.gsub("-", ""), "%Y%m%d")
    end_date = Date.strptime(end_date_str.gsub("-", ""), "%Y%m%d")
   
    while start_date <= end_date
        if start_date.day == 1 and start_date.wday == SUNDAY:
            count += 1
        end
        start_date += 1
    end
   
    return count
end




#
# Test Code
#



#
# Main
#
test_case
puts solution