Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of Friday's that fall on the 13th within a given year

I would like to create a function that goes through the months of a given year, calculates how many Fridays fall on the 13th, and returns that number. So far this is what I have:

function numberOfFridaythe13thsIn(jahr){
    var d = new Date();
    d.setFullYear(jahr, 0, 13);
    var counter = 0;
    var months = 0;
    while(months <= 11) {
        months++;
        if(d.getDay() == 5 && d.getDate() == 13) {
          counter++;
       }
    }
    return counter;                            
}

I am imagining this code starts on January 13th of a given year, has a counter where the sum of days will go, and will cycle through the months. I know my code is off, but can I get some guidance?

like image 524
vehcklox Avatar asked Jan 07 '23 06:01

vehcklox


2 Answers

Try this:

function numberOfFridaythe13thsIn(jahr){
    var d = new Date();
    var counter = 0;
    var month;

    for(month=0;month<12;month++)
    {
     d.setFullYear(jahr, month,13);
        if (d.getDay() == 5)
        {
          counter++;
        }
    }

    return counter;                            
}

Basically, there are only twelve days in the year with date 13. So, we simply loop through each one and check if it is a Friday or not.

like image 103
shree.pat18 Avatar answered Jan 09 '23 19:01

shree.pat18


The important bit you were missing was to update the date on every loop iteration.

function numberOfFridaythe13thsIn(jahr) {
    var count = 0;
    for (var month=0; month<12; month++) {
        var d = new Date(jahr,month,13);
        if(d.getDay() == 5){
          count++;
       }
    }
    return count;                            
}

console.log(numberOfFridaythe13thsIn(2015));
like image 25
Julian Avatar answered Jan 09 '23 19:01

Julian