Solved ProjectEuler/019: php, ruby
This commit is contained in:
25
ProjectEuler/019/desc.yml
Normal file
25
ProjectEuler/019/desc.yml
Normal file
@ -0,0 +1,25 @@
|
||||
title: How many Sundays fell on the first of the month during the twentieth century?
|
||||
url: http://projecteuler.net/problem=19
|
||||
|
||||
desc: |
|
||||
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)?
|
||||
|
||||
|
||||
solution: Instead of using buildtin DateTime language features this use a homemade algorithm
|
||||
|
||||
solutions:
|
||||
solve.php:
|
||||
desc: Basic solution
|
||||
language: php
|
||||
solve.rb:
|
||||
desc: Basic solution
|
||||
language: ruby
|
38
ProjectEuler/019/solve.php
Normal file
38
ProjectEuler/019/solve.php
Normal file
@ -0,0 +1,38 @@
|
||||
<?php
|
||||
$days_in_month = array(
|
||||
1 => 31,
|
||||
2 => 28,
|
||||
3 => 31,
|
||||
4 => 30,
|
||||
5 => 31,
|
||||
6 => 30,
|
||||
7 => 31,
|
||||
8 => 31,
|
||||
9 => 30,
|
||||
10 => 31,
|
||||
11 => 30,
|
||||
12 => 31
|
||||
);
|
||||
$day_cycle = 0;
|
||||
for($year=1900; $year <= 2000; $year++) {
|
||||
for($month=1; $month <= 12; $month++) {
|
||||
|
||||
$cdates = $days_in_month[$month];
|
||||
if($month == 2) {
|
||||
if($year % 4 == 0) {
|
||||
$cdates = 29;
|
||||
}
|
||||
if($years % 100 == 0) {
|
||||
$cdates = 28;
|
||||
}
|
||||
if($years % 400 == 0) {
|
||||
$cdates = 29;
|
||||
}
|
||||
}
|
||||
$day_cycle += $cdates;
|
||||
if($day_cycle % 7 == 0) {
|
||||
if($year >= 1901) {$sum++; }
|
||||
}
|
||||
}
|
||||
}
|
||||
echo $sum;
|
9
ProjectEuler/019/solve.rb
Normal file
9
ProjectEuler/019/solve.rb
Normal file
@ -0,0 +1,9 @@
|
||||
require "date"
|
||||
sundays = 0
|
||||
(1901..2000).each do |year|
|
||||
(1..12).each do |month|
|
||||
dt = Date.new(year,month,1)
|
||||
sundays += (dt.wday == 0) ? 1 : 0
|
||||
end
|
||||
end
|
||||
puts sundays
|
Reference in New Issue
Block a user