Skip to content

Commit 1ff709e

Browse files
committed
[Solution] Project euler challenge 19 with tests
1 parent 6fe21d2 commit 1ff709e

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Project-Euler/Problem019.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Problem 19 - Counting Sundays
3+
*
4+
* @see {@link https://projecteuler.net/problem=19}
5+
*
6+
* You are given the following information, but you may prefer to do some research for yourself.
7+
* 1 Jan 1900 was a Monday.
8+
* Thirty days has September,
9+
* April, June and November.
10+
* All the rest have thirty-one,
11+
* Saving February alone,
12+
* Which has twenty-eight, rain or shine.
13+
* And on leap years, twenty-nine.
14+
* A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
15+
* How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
16+
*
17+
* @author ddaniel27
18+
*/
19+
20+
// Check if a year is a leap year
21+
// A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
22+
function isLeapYear(year) {
23+
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
24+
}
25+
26+
function problem19() {
27+
let sundaysCount = 0 // Count of Sundays
28+
let dayOfWeek = 2 // 1st Jan 1900 was a Monday, so 1st Jan 1901 was a Tuesday
29+
30+
for (let year = 1901; year <= 2000; year++) {
31+
// From 1901 to 2000
32+
for (let month = 1; month <= 12; month++) {
33+
// From January to December
34+
if (dayOfWeek === 0) {
35+
// If it's a Sunday (0 is Sunday, 1 is Monday, ..., 6 is Saturday)
36+
sundaysCount++
37+
}
38+
39+
let daysInMonth = 31
40+
if (month === 4 || month === 6 || month === 9 || month === 11) {
41+
// April, June, September, November
42+
daysInMonth = 30
43+
} else if (month === 2) {
44+
// February
45+
daysInMonth = isLeapYear(year) ? 29 : 28
46+
}
47+
48+
dayOfWeek = (dayOfWeek + daysInMonth) % 7 // Calculate the day of the week
49+
}
50+
}
51+
52+
return sundaysCount
53+
}
54+
55+
export { problem19 }

Project-Euler/test/Problem019.test.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { problem19 } from '../Problem019.js'
2+
3+
describe('checking sundays during the twentieth century', () => {
4+
// Project Euler Challenge Check
5+
test('result should be 171', () => {
6+
expect(problem19()).toBe(171)
7+
})
8+
})

0 commit comments

Comments
 (0)