Sandbox | Index | gfrlog | Contact
Problem #19

You are given the following information, but you may prefer to do some research for yourself.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

Erlang: Running time = 0.205s
p19()->
	put(months,{31,28,31,30,31,30,31,31,30,31,30,31}),
	io:format("~w~n",[p19({1,0,1900},0)]).
p19({_,_,2001},R)->R;
p19({D,M,1900},R)->
	p19(p19_next({D,M,1900}),R);
p19({0,M,Y},R)->
	p19(p19_next({0,M,Y}),R+1);
p19(Day,R)->
	p19(p19_next(Day),R).
p19_next({D,M,Y})->
	{(D+element(M+1,get(months)) + if M==1,(Y rem 4) ==0->1; true->0 end ) rem 7,(M+1) rem 12,
		Y + if M==11->1; true->0 end}.

Ruby: Running time = 0.021s
def p19
  dm=[31,28,31,30,31,30,31,31,30,31,30,31]
  day=1
  year=1900
  month=0
  count=0
  while(year<2001)
    count+=1 if day==0 and year.between?(1901,2000)
    day+=dm[month]
    month=(month+1)%12
    day+=1 if month==2 and year%4==0 and year > 1900
    year+=1 if month==0
    day=day%7
  end
  puts count 
end