Tell us what’s happening:
So I’ve been trying to solve this problem by brute force and I am so close! The only test-case I am not passing is the 2nd one where I should get an output of 9 instead of 10. I’m going to take a break and come back to this but if anyone can spot where I am going wrong and give me a hint I’d appreciate it!
Your code so far
function countingSundays(firstYear, lastYear) {
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let startYearIndex = 12*(firstYear-1901)
let firstSunday = init()[startYearIndex]
let sundays = [firstSunday]
generate(firstYear, lastYear)
function calcSundays(daysInMonth, sundayInPrevMonth){
let daysLeft = daysInMonth - sundayInPrevMonth
let daysIntoNext = daysLeft%7
let firstSundayNextMonth = 7-daysIntoNext
return firstSundayNextMonth
}
function init(){
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let sundays = [6]
for (let i = 1901; i <= 2000; i++){
if (i % 4 === 0 || i % 100 === 0 && i % 400 === 0){
daysInMonth[1] = 29
} else {
daysInMonth[1] = 28
}
for (let j = 0; j < 12; j++){
sundays.push(calcSundays(daysInMonth[j], sundays[sundays.length-1]))
}
}
return sundays
}
function generate(firstYear, lastYear){
for (let i = firstYear; i <= lastYear; i++){
if (i % 4 === 0 || i % 100 === 0 && i % 400 === 0){
daysInMonth[1] = 29
} else {
daysInMonth[1] = 28
}
for (let j = 0; j < 12; j++){
sundays.push(calcSundays(daysInMonth[j], sundays[sundays.length-1]))
}
}
}
return sundays.filter((x)=>x===1).length
}
countingSundays(1943, 1946);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-19-counting-sundays/