41
\$\begingroup\$

This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

1954

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

1900
2100
2200
2300

Test cases:

1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y 

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 50798; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
  • 9
    \$\begingroup\$ You should be more clear: A given year is a leap year if and only if it is (divisible by 4)∧((divisible by 100)→(divisible by 400)). \$\endgroup\$ – LegionMammal978 May 26 '15 at 11:34
  • \$\begingroup\$ Your input will have no newlines or trailing spaces. Dang it, that would have saved me 2 bytes... \$\endgroup\$ – Dennis May 26 '15 at 17:10
  • 2
    \$\begingroup\$ You should extend the accepted input range to AD 1601 thru 2400. This covers two 400-year Gregorian cycles (which proleptically start on Monday). \$\endgroup\$ – David R Tribble May 26 '15 at 18:17
  • 2
    \$\begingroup\$ Does falsy if leap year and truthy if not a leap year count as "clearly tells the user if it is or isn't"? \$\endgroup\$ – lirtosiast May 28 '15 at 21:27
  • \$\begingroup\$ @lirtosiast I think so. A lot of user assume so. \$\endgroup\$ – aloisdg moving to codidact.com Jul 20 '16 at 13:58

69 Answers 69

1 2
3
1
\$\begingroup\$

W d, 10 8 bytes

Ö♦Ç⌂╬`§Γ

Explanation:

Uncompressed:

25m4&16|m!
25m        % If the input is modulo-able by 25:
   4&      % Return 4
     16|   % Otherwise, return 16
        m! % Modulo input by the value. Negate the value.
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

MATLAB + Aerospace Toolbox, 9 bytes

@leapyear

Anonymous function that determines if the passed year is a leap year, returning 1 for leap and 0 for not.

Ok so MATLAB has a built-in... But there we are.


Octave, 13 bytes

@is_leap_year

Try it online!

Octave also has a built-in... cost's 4 more bytes than MATLAB though.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Whitespace, 103 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input][S S S T T   S S T   N
_Push_25][T S T T   _Modulo][N
T   S T N
_If_0_jump_to_Label_TRUE][S S S T   S S N
_Push_4][T  S T T   _Modulo][N
T   S S N
_If_0_jump_to_Label_LEAP][N
S N
N
_Jump_to_Label_PRINT][N
S S T   N
_Create_Label_TRUE][S S S T S S S S N
_Push_16][T S T T   _Modulo][N
T   S S N
_If_0_jump_to_Label_LEAP][N
S N
N
_Jump_to_Label_PRINT][N
S S S N
_Create_Label_LEAP][S S S T N
_Push_1][N
S S N
_Create_Label_PRINT][T  N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Explanation in pseudo-code:

Integer i = STDIN-input as integer
If i modulo-25 is 0:
  If i modulo-16 is 0:
    Print 1
  Else:
    Print 0
Else-if i modulo-4 is 0:
  Print 1
Else:
  Print 0

Example runs:

Input: 1936

Command     Explanation                Stack            Heap       STDIN    STDOUT   STDERR

SSSN        Push 0                     [0]              {}
SNS         Duplicate top (0)          [0,0]            {}
SNS         Duplicate top (0)          [0,0,0]          {}
TNTT        Read STDIN as integer      [0,0]            {0:1936}   1936
TTT         Retrieve at heap 0         [0,1936]         {0:1936}
SNS         Duplicate top (1936)       [1936,1936]      {0:1936}
SSSTTSSTN   Push 25                    [1936,1936,25]   {0:1936}
TSTT        Modulo                     [1936,11]        {0:1936}
NTSTN       If 0: Jump to Label_TRUE   [1936]           {0:1936}
SSSTSSN     Push 4                     [1936,4]         {0:1936}
TSTT        Modulo                     [0]              {0:1936}
NTSSN       if 0: Jump to Label_LEAP   []               {0:1936}
NSSSN       Create Label_LEAP          []               {0:1936}
SSSTN       Push 1                     [1]              {0:1936}
NSSN        Create Label_PRINT         [1]              {0:1936}
TNST        Print top as integer       []               {0:1936}            1
                                                                                     error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).

Input: 2400

Command     Explanation                Stack            Heap       STDIN    STDOUT   STDERR

SSSN        Push 0                     [0]              {}
SNS         Duplicate top (0)          [0,0]            {}
SNS         Duplicate top (0)          [0,0,0]          {}
TNTT        Read STDIN as integer      [0,0]            {0:2400}   2400
TTT         Retrieve at heap 0         [0,2400]         {0:2400}
SNS         Duplicate top (2400)       [2400,2400]      {0:2400}
SSSTTSSTN   Push 25                    [2400,2400,25]   {0:2400}
TSTT        Modulo                     [2400,0]         {0:2400}
NTSTN       If 0: Jump to Label_TRUE   [2400]           {0:2400}
NSSTN       Create Label_TRUE          [2400]           {0:2400}
SSSTSSSSN   Push 16                    [2400,16]        {0:2400}
TSTT        Modulo                     [0]              {0:2400}
NTSSN       If 0: Jump to Label_LEAP   []               {0:2400}
NSSSN       Create Label_LEAP          []               {0:2400}
SSSTN       Push 1                     [1]              {0:2400}
NSSN        Create Label_PRINT         [1]              {0:2400}
TNST        Print top as integer       []               {0:2400}            1
                                                                                     error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).

Input: 1991

Command     Explanation                Stack            Heap       STDIN    STDOUT   STDERR

SSSN        Push 0                     [0]              {}
SNS         Duplicate top (0)          [0,0]            {}
SNS         Duplicate top (0)          [0,0,0]          {}
TNTT        Read STDIN as integer      [0,0]            {0:1991}   1991
TTT         Retrieve at heap 0         [0,1991]         {0:1991}
SNS         Duplicate top (1991)       [0,1991,1991]    {0:1991}
SSSTTSSTN   Push 25                    [0,1991,1991,25] {0:1991}
TSTT        Modulo                     [0,1991,16]      {0:1991}
NTSTN       If 0: Jump to Label_TRUE   [0,1991]         {0:1991}
SSSTSSN     Push 4                     [0,1991,4]       {0:1991}
TSTT        Modulo                     [0,3]            {0:1991}
NTSSN       if 0: Jump to Label_LEAP   [0]              {0:1991}
NSSN        Create Label_PRINT         [0]              {0:1991}
TNST        Print top as integer       []               {0:1991}            0
                                                                                     error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

ActionScript 2.0, 49 bytes

function a(b){trace(!(b%4)&&b%100+!(b%400)?1:0);}
function a(b){                                  } - define a function
              trace(                          );  - that outputs
                                          ?       - if
                    !(b%4)                        - the input divides by 4
                          &&                      - and
                            b%100                 - doesn't divide by 100
                                 +                - plus
                                  !(b%400)        - does divide by 400
                                           1:0    - 1, else 0

Not a very good explanation, and I might have swapped some stuff, but this still confuses me, so this is the best you're going to get.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C (gcc), 33 bytes

f(i,a){a=!(i%4|!(i%100)&&i%400);}

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 19 bytes

y=>!(y%25?y%4:y%16)

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Swift, 82 bytes

func l(y:Int){y%4==0 && (y%100 != 0 || y%400==0) ?print("Y"):print("N")}
l(y:1936)

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 9 7 bytes

т‰0Kθ4Ö

Try it online or verify all test cases.

Explanation:

т‰         # Divmod the (implicit) input by 100
           #  i.e. 1900 → [19,00]
           #  i.e. 1936 → [19,36]
           #  i.e. 1991 → [19,91]
           #  i.e. 2000 → [20,00]
  0K       # Remove all 0s
           #  i.e. [19,00] → [19]
           #  i.e. [19,36] → [19,36]
           #  i.e. [19,91] → [19,91]
           #  i.e. [20,00] → [20]
    θ      # Pop and get the last item
           #  i.e. [19] → 19
           #  i.e. [19,36] → 36
           #  i.e. [19,91] → 91
           #  i.e. [20] → 20
     4Ö    # Check if it's divisible by 4 (and output the result implicitly)
           #  i.e. 19 → 0 (falsey)
           #  i.e. 36 → 1 (truthy)
           #  i.e. 91 → 0 (falsey)
           #  i.e. 20 → 1 (truthy)
| improve this answer | |
\$\endgroup\$
-2
\$\begingroup\$

Reality, 1 byte

L

input via stdinput


The language was made after the challenge

| improve this answer | |
\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy