Purpose of the code at the 1st comment.
I am aware that
first two constants can be replaced by function
or
the second constant can be generated by mapping from the first one.
But I don’t see any issues with my implementation also.
Main question, however
did I manage to name variables properly?
/*
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
*/
//CONSTANTS
//serial numbers of starting days of months
//for usual(non-leap) years
const firstsUsual = [
1, //jan
32, //feb
60, //mar
91, //apr
121, //may
152, //jun
182, //jul
213, //aug
244, //sep
274, //oct
305, //nov
335 //dec
]
//for leap years
const firstsLeap = [
1, //jan
32, //feb
61, //mar
92, //apr
122, //may
153, //jun
183, //jul
214, //aug
245, //sep
275, //oct
306, //nov
336 //dec
]
//1st jan 1900 >>> Monday
//thus
const sunday1900 = 7;
//HELPER FUNCTIONS
//UNIT1
//to check year: leap or not
const isLeap = (year) => {
return (year % 4 === 0 && year !== 1900)
? true : false;
}
//UNIT2
//to get serial number of the first sunday
//of the given year
const getFirstSunday = (year) => {
if (year === 1900) {return sunday1900;}
let firstSunday = sunday1900;
for (let i = 1901; i <= year; i++) {
if (isLeap(i - 1)) {firstSunday -= 2;}
else {firstSunday --;}
if (firstSunday === 0) {firstSunday = 7;}
else if (firstSunday === -1){firstSunday = 6;}
}
return firstSunday;
}
//UNIT3
//to count sundays which also were
//1st days of month in the given year
/*
logic
if 1st sunday >>> 7
all sundays >>> 7, 14, 21, 28...
thus
sunday % 7 === 0
if 1st sunday >>> 3
all sundays >>> 3, 10, 17, 24...
thus
sunday % 7 === 1st sunday
*/
const countFirstsAndAlsoSundays = (year, firstSunday) => {
let counter = 0;
let listOfFirsts;
if (isLeap(year)) {
listOfFirsts = firstsLeap;
}
else {
listOfFirsts = firstsUsual;
}
for (let day of listOfFirsts) {
if (firstSunday === 7) {
if (day % 7 === 0) {counter++;}
}
else {
if (day % 7 === firstSunday) {counter++;}
}
}
return counter;
}
//MAIN UNIT
//sum results from UNIT3 for years in the give range
function countingSundays(firstYear, lastYear) {
let sundaysInRange = 0;
for (let year = firstYear; year <= lastYear; year++) {
sundaysInRange += countFirstsAndAlsoSundays(
year, getFirstSunday(year)
)
}
return sundaysInRange;
}
countingSundays(1943, 1946);