12 Replies - 4615 Views - Last Post: 18 June 2015 - 02:33 PM

#1 jward01   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-June 15

Help with JavaScript Function: Print out the next 20 leap years

Posted 16 June 2015 - 03:09 PM

I have a question for school that is stumping me. I don't have an editor to run the Javascript in, so I am using CodeAcademy and JSFiddle to run it. Both are saying "Un-expected 'else' found.

QUESTION: Write a function that takes ANY year given by user, and prints out the NEXT 20 leap years.

Can someone please look over my code and see if there are any errors?


Also I fear that my '=== and "!==" may be incorrect as well.


Thanks!


var year = prompt("please input a year to find out the next 20 years");
var counter = 20;
var result=true;


function leapyear(year, counter, result) {
    while (counter >= 0) {

        if ((year % 4 === 0) && (year % 100 !== 0)||(year % 400 === 0)); {
            result = true;
            console.log(year);
            year++;
            counter--;
        } 
        else {
        year++;
        }    
    }
}





**If you know of any ways I can compile and run this code that would be of great help! Currently I am using CodeAcademy and JSFiddle which are lackluster.

Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: Help with JavaScript Function: Print out the next 20 leap years

#2 jward01   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-June 15

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 16 June 2015 - 03:16 PM

Ok, I discovered an un-proper ; after the IF statement.

Now it is correct syntax wise, I just don't know if it would ACTUALLY output the next 20 leap years, as I have no way of testing/running the code.

Any help/advice?

Thanks!
Was This Post Helpful? 0
  • +
  • -

#3 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2673
  • View blog
  • Posts: 7,892
  • Joined: 15-January 14

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 16 June 2015 - 04:40 PM

You have a web browser, right? That will run it. See the links in my signature to the various browser developer tools. Some of them use F12 to open the developer tools, and then you need to find your way to the Console tab. You can paste code there and have the browser run it. If you want output to appear in the console, pass whatever you want to print to console.log or console.info.
Was This Post Helpful? 1
  • +
  • -

#4 jward01   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-June 15

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 16 June 2015 - 04:49 PM

Thanks!! It did run and the developer tool 'trick' was very helpful!!

This post has been edited by Dormilich: 16 June 2015 - 06:45 PM

Was This Post Helpful? 0
  • +
  • -

#5 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4271
  • View blog
  • Posts: 13,521
  • Joined: 08-June 10

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 16 June 2015 - 06:53 PM

Notes:
- your result variable does nothing
- you can leave the leap year algorithm completely up to the Date object
Was This Post Helpful? 1
  • +
  • -

#6 JMRKER   User is offline

  • D.I.C Addict
  • member icon

Reputation: 134
  • View blog
  • Posts: 868
  • Joined: 25-October 08

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 16 June 2015 - 08:50 PM

Another possibility...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Next 20 Leap Years </title>
</head>
<body>
<input type="text" id="beginYear" value="1890">
<button onclick="list20LeapYears()">Next 20 leap years</button>
<pre id="debug"></pre>

<script type="text/javascript">
// From: http://javascript.about.com/library/bldayyear.htm
Date.prototype.getDOY = function() {  // returns day-of-year (0...364, [365 leap year])
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((this - onejan) / 86400000);
}
function list20LeapYears() {
  var nd, ld, ly = [], yr = document.getElementById('beginYear').value*1;
  while (ly.length < 20) {
    nd = new Date(yr,11,31);
    ld = nd.getDOY();
    if (ld == 365) { ly.push(yr); } // found leap year when ld=365
    yr++;
  }
  document.getElementById('debug').innerHTML = ly.join('<br>')+'<hr>';
}
</script>
</body>
</html>

Was This Post Helpful? 1
  • +
  • -

#7 felgall   User is offline

  • D.I.C Regular

Reputation: 68
  • View blog
  • Posts: 365
  • Joined: 22-February 14

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 17 June 2015 - 12:27 PM

function isLeapYear( year ) {
    return (new Date( year, 1, 29 )).getDate() === 29 );
}


will correctly identify a year as being a leap year or not between 1582 and 4881.

Before 1582 the leap year rules were different (every 4th year with no exceptions)

The Javascript Date processing likely does not take into account the third leap year rule that adds an extra leap year every 3300 years - making 4882 and 8182 leap years even though they are not divisible by 4.
Was This Post Helpful? 1
  • +
  • -

#8 jward01   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-June 15

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 17 June 2015 - 02:13 PM

View PostJMRKER, on 16 June 2015 - 08:50 PM, said:

Another possibility...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Next 20 Leap Years </title>
</head>
<body>
<input type="text" id="beginYear" value="1890">
<button onclick="list20LeapYears()">Next 20 leap years</button>
<pre id="debug"></pre>

<script type="text/javascript">
// From: http://javascript.about.com/library/bldayyear.htm
Date.prototype.getDOY = function() {  // returns day-of-year (0...364, [365 leap year])
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((this - onejan) / 86400000);
}
function list20LeapYears() {
  var nd, ld, ly = [], yr = document.getElementById('beginYear').value*1;
  while (ly.length < 20) {
    nd = new Date(yr,11,31);
    ld = nd.getDOY();
    if (ld == 365) { ly.push(yr); } // found leap year when ld=365
    yr++;
  }
  document.getElementById('debug').innerHTML = ly.join('<br>')+'<hr>';
}
</script>
</body>
</html>


Thanks for the help by writing out this code! I will study it to understand it and the commands, as I am a somewhat newbie and still need to learn the commands you used. That seems like a very efficient code!


View Postfelgall, on 17 June 2015 - 12:27 PM, said:

function isLeapYear( year ) {
    return (new Date( year, 1, 29 )).getDate() === 29 );
}


will correctly identify a year as being a leap year or not between 1582 and 4881.

Before 1582 the leap year rules were different (every 4th year with no exceptions)

The Javascript Date processing likely does not take into account the third leap year rule that adds an extra leap year every 3300 years - making 4882 and 8182 leap years even though they are not divisible by 4.


Nice use of the get date command! Another user suggested I use that as well. I need to learn that command as well as I only know the basic comparison operators. It is good to know there are much more efficient and easier ways of running the program/code than what I did.

--------------------

Below is my 'final' working code. Thanks for all the help everyone. It definitely appears I need to learn more commands so that my code is more efficient and shorter. I will study up on them and learn!! Thanks again!!

var year = prompt("please input a year to find out the next 20 years");
var counter = 20;

function leapYearCalc(year, counter) {
    while (counter >= 0) {

        if ((year % 4 === 0) && (year % 100 !== 0)||(year % 400 === 0)) {
            console.log(year);
            year++;
            counter--;
        } 
        else {
        year++;
        }    
    }
}

leapYearCalc(year, counter);


Was This Post Helpful? 0
  • +
  • -

#9 JMRKER   User is offline

  • D.I.C Addict
  • member icon

Reputation: 134
  • View blog
  • Posts: 868
  • Joined: 25-October 08

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 17 June 2015 - 07:15 PM

Using 'felgall's function, you can shorten it quit a bit.
<script>
function isLeapYear( year ) { return ( (new Date( year, 1, 29 )).getDate() === 29); }

function leapYearCalc(yr) {
  var counter = 20;
  while (counter > 0) {
    if (isLeapYear(yr)) {
      counter--;
      console.log(yr); document.writeln(yr+'<br>');
    }
    yr++;
  } 
}

var year = prompt("please input a year to find out the next 20 years");
leapYearCalc(year);
</script>


I thought you requested the next 20 leap years.

Quote

QUESTION: Write a function that takes ANY year given by user, and prints out the NEXT 20 leap years.

Your code listed the leap years found in the next 20 years.
Slightly different results.

Note, you should keep as many variables local to the function
as possible (ie, counter and year) to avoid possible conflicts
with other functions you might develop in the future as your
scripts become more complicated.

In your code the variable 'counter' is global and 'year' is both local and global.
Will lead to many problems in longer and more function dependent scripts.

Good luck with your studies.
:)
Was This Post Helpful? 1
  • +
  • -

#10 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 18 June 2015 - 04:10 AM

Actually, I like the classic year check. Note, I believe you got the parens wrong.

I'd also use more, shorter, functions. e.g.
function askUser(years) {
    leapYearCalc(prompt("please input a year to find out the next " + years + " years"), years);
}

function isLeap(y) { return ((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0); }

function nextLeapYear(y) {
    while(!isLeap(y)) { y++; }
    return y;
}

function leapYearCalc(year, counter) {
    for(var i=0; i<counter; i++) {
        year = nextLeapYear(year);
        console.log(year);
        year++;
    }
}



For more fun, if leapYearCalc actually returned an array, you could do with the results as you like. Or you could could pass it a callback to send the results to. Iterators and generators in Javascript are a little wonky, sadly, but you could do that too.
Was This Post Helpful? 1
  • +
  • -

#11 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2673
  • View blog
  • Posts: 7,892
  • Joined: 15-January 14

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 18 June 2015 - 09:34 AM

I wondered about the overhead of using the date object, and it looks like straight modulus math is about 500 times faster than using the date object.

var start_year = 1600;
var rounds = 1000;

function leapYearCalc1(year, counter) {
    while (counter >= 0) {
        if ((year % 4 === 0) && (year % 100 !== 0)||(year % 400 === 0)) {
            //console.log(year);
            counter--;
        } 
        year++;
    }
}

function leapYearCalc2(year, counter) {
    while (counter >= 0) {
        if ((new Date( year, 1, 29 )).getDate() === 29) {
            //console.log(year);
            counter--;
        } 
        year++;
    }
}


var start_time = Date.now();
for (var j = 0; j < rounds; j++) {
  var year = start_year;
  var counter = 100;
  leapYearCalc1(year, counter);  
}
var time1 = Date.now() - start_time;

start_time = Date.now();
for (var j = 0; j < rounds; j++) {
  var year = start_year;
  var counter = 100;
  leapYearCalc2(year, counter);  
}
var time2 = Date.now() - start_time;

console.log('Method 1: ' + time1 + ', method 2: ' + time2);


This is for 1000 rounds of calculating 100 leap years since 1600. For the first method I get 4 or 5 milliseconds, and the second is around 1970 - 2050.
Was This Post Helpful? 1
  • +
  • -

#12 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4271
  • View blog
  • Posts: 13,521
  • Joined: 08-June 10

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 18 June 2015 - 09:48 AM

even though the Date object is slower (not a surprise) is doesn’t require you to know the algorithm for the leap year calculation. hence one important source for errors eliminated.
Was This Post Helpful? 1
  • +
  • -

#13 jward01   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-June 15

Re: Help with JavaScript Function: Print out the next 20 leap years

Posted 18 June 2015 - 02:33 PM

View PostArtificialSoldier, on 18 June 2015 - 09:34 AM, said:

I wondered about the overhead of using the date object, and it looks like straight modulus math is about 500 times faster than using the date object.
[snip]
This is for 1000 rounds of calculating 100 leap years since 1600. For the first method I get 4 or 5 milliseconds, and the second is around 1970 - 2050.

Thank you!! You are a boss. Thanks for using the Date function as well. It is a good example of that in use. I will use this for reference now and in the future. Thanks!!

View PostDormilich, on 18 June 2015 - 09:48 AM, said:

even though the Date object is slower (not a surprise) is doesn’t require you to know the algorithm for the leap year calculation. hence one important source for errors eliminated.



That is very good to know!! It is a nice shortcut too. More knowledge more better!!

This post has been edited by Dormilich: 19 June 2015 - 12:21 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1