Skip to content

Commit 5844242

Browse files
ddaniel27appgurueu
andauthored
[Solution] Project euler challenge 19 with tests (TheAlgorithms#1659)
* [Solution] Project euler challenge 19 with tests * update leap year function * Remove unnecessary, confusingly placed comments --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent 0182bca commit 5844242

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Project-Euler/Problem019.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
import { isLeapYear } from '../Maths/LeapYear'
20+
21+
function problem19() {
22+
let sundaysCount = 0 // Count of Sundays
23+
let dayOfWeek = 2 // 1st Jan 1900 was a Monday, so 1st Jan 1901 was a Tuesday
24+
25+
for (let year = 1901; year <= 2000; year++) {
26+
for (let month = 1; month <= 12; month++) {
27+
if (dayOfWeek === 0) {
28+
// If it's a Sunday (0 is Sunday, 1 is Monday, ..., 6 is Saturday)
29+
sundaysCount++
30+
}
31+
32+
let daysInMonth = 31
33+
if (month === 4 || month === 6 || month === 9 || month === 11) {
34+
// April, June, September, November
35+
daysInMonth = 30
36+
} else if (month === 2) {
37+
// February
38+
daysInMonth = isLeapYear(year) ? 29 : 28
39+
}
40+
41+
dayOfWeek = (dayOfWeek + daysInMonth) % 7 // Calculate the day of the week
42+
}
43+
}
44+
45+
return sundaysCount
46+
}
47+
48+
export { problem19 }

Project-Euler/test/Problem019.test.js

Lines changed: 8 additions & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy