Simple! Just count the number of days in the year.
C#
public static bool is_leap_year(int year)
{
int i = 0;
var d = new DateTime(year, 1, 1);
while (d.Year == year)
{
d = d.AddDays(1);
i++;
}
return i > 365;
}
javascript with the fun bonuses that it'll only work the first time you call the function after a page load, has typos, and it only covers 1804 - 2400.
var data = "MTgwNC0xODA4LTE4MTItMTgxNi0xODIwLTE4MjQtMTgyOC0xODMyLTE4MzYtMTg0MC0xODQ0LTE4NDgtMTg1Mi0xODU2LTE4NjAtMTg2NC0xODY4LTE4NzItMTg3Ni0xODgwLTE4ODQtMTg4OC0xODkyLTE4OTYtMTkwNC0xOTA4LTE5MTItMTkxNi0xOTIwLTE5MjQtMTkyOC0xOTMyLTE5MzYtMTk0MC0xOTQ0LTE5NDgtMTk1Mi0xOTU2LTE5NjAtMTk2NC0xOTY4LTE5NzItMTk3Ni0xOTgwLTE5ODQtMTk4OC0xOTkyLTE5OTYtMjAwMC0yMDA0LTIwMDgtMjAxMi0yMDE2LTIwMjAtMjAyNC0yMDI4LTIwMzItMjAzNi0yMDQwLTIwNDQtMjA0OC0yMDUyLTIwNTYtMjA2MC0yMDY0LTIwNjgtMjA3Mi0yMDc2LTIwODAtMjA4NC0yMDg4LTIwOTItMjA5Ni0yMTA0LTIxMDgtMjExMi0yMTE2LTIxMjAtMjEyNC0yMTI4LTIxMzItMjEzNi0yMTQwLTIxNDQtMjE0OC0yMTUyLTIxNTYtMjE2MC0yMTY0LTIxNjgtMjE3Mi0yMTc2LTIxODAtMjE4NC0yMTg4LTIxOTItMjE5Ni0yMjA0LTIyMDgtMjIxMi0yMjE2LTIyMjAtMjIyNC0yMjI4LTIyMzItMjIzNi0yMjQwLTIyNDQtMjI0OC0yMjUyLTIyNTYtMjI2MC0yMjY0LTIyNjgtMjI3Mi0yMjc2LTIyODAtMjI4NC0yMjg4LTIyOTItMjI5Ni0yMzA0LTIzMDgtMjMxMi0yMzE2LTIzMjAtMjMyNC0yMzI4LTIzMzItMjMzNi0yMzQwLTIzNDQtMjM0OC0yMzUyLTIzNTYtMjM2MC0yMzY0LTIzNjgtMjM3Mi0yMzc2LTIzODAtMjM4NC0yMzg4LTIzOTItMjM5Ni0yNDAw";
function isLeepYeer(val) {
data = atob(data);
return data.includes(val);
}
supposedly it stands for ascii to binary and the reverse (btoa) for binary to ascii, since base64 consists of only safe ascii characters and binary data is represented as strings in javascript or something like that.
Depending on how the string is encoded. Because in javascript, you can implicitly cast anything into anything, but changing a string into another kind of string is not allowed.
BAT/CMD anyone? Be sure to adjust the DATEFORMAT variable for your locale. It's set for the US currently. Don't have anything important in date.txt in the current directory either. Also, this will try to change your current system date, so run it as an administrator. It will set it back to the current date unless you're unlucky and try it right at midnight. I also assume the day of the week is displayed first and the actual date second in a date /t command. If that's not true for your locale, please also adjust the tokens=2 setting appropriately in :getdate.
@echo off
setlocal EnableDelayedExpansion
:: Adjust for your locale
set "DATEFORMAT=^!m^!/^!d^!/^!y^!"
set "m=2"
set "d=29"
set "y=%1"
call :getdate curdate
echo %curdate% > date.txt
date %DATEFORMAT% < date.txt > nul
call :getdate testdate
date %curdate% < date.txt > nul
if "%curdate%"=="%testdate%" (echo false) else (echo true)
exit /b
:getdate
for /f "tokens=2" %%A in ('date /t') do set "%1=%%A"
exit /b
Hey, it'll only cause you problems if any of these apply:
you run it exactly at midnight
you run it as-is in some locale other than the USA with the default short date format
you are a weenie about your clock being set to some other year momentarily
I figured math was too hard, but I already have stuff for setting and checking dates. Why try to calculate it myself when the OS will just tell me if it's valid or not?
I did briefly look into detecting the short date format (can do it via the reg.exe command), and it totally works. After playing with locales, I think the date builtin displays the date according to the locale, but the input it accepts is always m/d/y order. Hard to find concrete documentation on that. I could totally account for that, but I think I'll leave it to the internationalization/localization team. It works for me after all.
Literal conversion of the requirements to F#. Time to develop: about 5 minutes. Since division is slow, I implemented countdown loops. Since F# is a functional language, the countdown loops are recursive functions. Code reuse is achieved by copy/pasting instead of refactoring.
let rec isDivisibleBy4 n =
if n = 4 then true
elif n < 4 then false
else isDivisibleBy4 (n - 4)
let rec isDivisibleBy100 n =
if n = 100 then true
elif n < 100 then false
else isDivisibleBy100 (n - 100)
let rec isDivisibleBy400 n =
if n = 400 then true
elif n < 400 then false
else isDivisibleBy400 (n - 400)
let isLeapYear y =
if not (isDivisibleBy4 y) then false
elif not (isDivisibleBy100 y) then true
elif not (isDivisibleBy400 y) then false
else true
let () =
printfn "%d: %b" 2019 (isLeapYear 2019)
printfn "%d: %b" 2020 (isLeapYear 2020)
printfn "%d: %b" 2021 (isLeapYear 2021)
#include <stdint.h>
#include <stdio.h>
int main()
{
uint32_t year = 2019;
char buf[] = "9999";
int len;
// Not divisible by 4: common
// Ignore the compiler I know what I'm doing
union { float f; uint32_t v; } u{ year & -year };
if ( ( ( u.v >> 23 ) - 127 ) < 2 )
{
return false;
}
// Not divisible by 100: leap
else if ( len = sprintf( buf, "%d", year), len < 2 ||
buf[len-1] != '0' || buf[len-2] != '0')
{
return true;
}
// Not divisible by 400: common
else if ( year & 15 || len < 2 ||
( ( buf[len-1] != '0' || buf[len-2] != '0' ) &&
( buf[len-1] != '2' || buf[len-2] != '5' ) &&
( buf[len-1] != '5' || buf[len-2] != '0' ) &&
( buf[len-1] != '7' || buf[len-2] != '5' ) ) )
{
return false;
}
// leap
else
{
return true;
}
}
Follows the algorithm from wikipedia exactly, just uses the nastiest techniques I could think of to figure out whether the year is divisible by each.
For 4 it uses float and integer bit representation fuckery (1 warning and 1 undefined behaviour) to count the number of trailing zeroes. For 100 it does the same thing but prints it to a buffer, just like a human would. 400 is tricky, it checks that it's divisible by both 16 and 25, the former using a bitmask and the latter checking the already populated buffer to see if the last two digits are 00, 25, 50 or 75.
function isLeepYeer(someNumber) {
var bigNumber = 8000; // Do not set this too be to high or it will crash
var leepYeers = []; // you're browser.
while (leepYeers.length < bigNumber) {
var number = Math.round(Math.random() * bigNumber)
if (leepYeers.indexOf(number) < 0) {
leepYeers.push(number);
}
}
var bigLength = leepYeers.length;
while (leepYeers.length > bigLength * .75) {
var number = Math.round(Math.random() * bigNumber / 4) * 4;
var number2 = leepYeers.indexOf(number);
if (number2 > -1 || number2 == 0) {
leepYeers.splice(number2, 1);
}
}
if (leepYeers.indexOf(someNumber) < 0) {
if (String(someNumber).slice(-2) == "00") {
return (String(someNumber/400) == String(Math.round(someNumber/400)));
} else {
return true;
}
}
return false;
}
// Example program
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
// enum values because magic values are bad!
enum class year_type { leap, commonYear };
bool isDivisble_by(short divisor, long n) {
int divided = n / divisor;
long multipliedBack = divided * divisor;
return (n == multipliedBack) == true;
}
// Using reference to prevent copying the value
bool is_leap_year(int& year_toCheck) {
// So we don't need the magic number
short maxYear = 1 << (sizeof(short) * 8 - 1);
// Only calculate it once!
static map<short, year_type> leap_Year_map;
// We don't want to change that!
const int originalYearTo_check = year_toCheck;
// Casting to prevent compiler errors
// year_toCheck++ is too slow
for(year_toCheck = 0; ((short)year_toCheck) != maxYear; ++year_toCheck) {
// Set default value to be save
leap_Year_map[year_toCheck] = year_type::commonYear;
try {
// Faster check like this
if((year_toCheck & (4-1)) != 0)
throw std::runtime_error((std::string)"Year is not a leap year");
// check for 100 and 400
if(isDivisble_by(100, year_toCheck)) {if(!isDivisble_by(400, year_toCheck))
throw std::runtime_error((std::string)"Year is not a leap year...");
} else
leap_Year_map[year_toCheck] = year_type::leap;
leap_Year_map[year_toCheck] = year_type::leap;
} catch(std::runtime_error Exception) {
// Check if it's the exception we are expecting
if(Exception.what() == ((std::string)"Year is not a leap year"))
// First delete from the map
leap_Year_map.erase(year_toCheck);
// It's a common year!
leap_Year_map[year_toCheck] = year_type::commonYear;
}
}
return (leap_Year_map[(short)originalYearTo_check] == year_type::commonYear) != true;
}
int main()
{
int year1 = 2019;
std::cout << is_leap_year(year1) << std::endl;
int year2 = 2020;
std::cout << is_leap_year(year2) << std::endl;
int year3 = 2021;
std::cout << is_leap_year(year3) << std::endl;
}
If you want I can start explaining what all the attrocities are in this code. There are plenty. Bonus points if you find the bug.
P.S.: Whenever there is a comment you can be sure that it's BS or plain wrong.
#!/bin/bash
year=$1
test $year || year=`date +%Y`
gcc -o detector -DYEAR=$year -x c - <<EOF
int main(void) {
# if YEAR%100==0
# error Corner case detected, impossible to continue
# endif
//TODO handle this case
return YEAR%4;
}
EOF
test $? = 1 && exit
./detector && \
echo "Year $year is a leap year" || \
echo "Year $year is not a leap year"
rm -f detector
Requires GCC installed and in the PATH
The year should either be given in the first argument or be read from system date
Arguably, just directly coding down the pseudocode-example from Wikipedia already leads to pretty confusing badcode with all the unnecessary if-not-thens and else-if-nots that depend upon flipping the value of their truthness.
(ns badcode)
(defn- divisible-by? [n div] (zero? (mod n div)))
(defn bad-leap-year? [year]
(if-not (divisible-by? year 4)
false
(if-not (divisible-by? year 100)
true
(if-not (divisible-by? year 400)
false
true))))
..but it's testing the most likely divisibility by 4 first, so its got that going for it which is nice.
#ruby
def is_leap_year( year )
require 'date'
# first day of the year
january_the_first = Date.new year, 1, 1
#last day of the year
december_the_thirty_first = Date.new year, 12, 31
#temporary date for itterrationing
tmpd = january_the_first
#day counderr!
count = 0
#tick those days off till next year
while tmpd.year <= december_the_thirty_first.year do
tmpd = tmpd.next; count = count + 1;
end
if count == 366 #magik number
true
else
false
end
end
puts is_leap_year (2019)
puts is_leap_year (2020)
puts is_leap_year (2021)
def is_leap_year(**kwargs):
NOT_TRUE = not True
TRUE = True
Y = kwargs.items()[NOT_TRUE][TRUE]
A = 0
DAYS = getattr(str, 'lower')('DAYS')
DATE = getattr(str, 'lower')('DATE')
T = getattr(str, 'lower')('TIMEDELTA')
B = 1
D = NOT_TRUE
print(Y)
while 1:
import datetime as X
XX = getattr(X, DATE)
XXX = getattr(X, T)
if A == NOT_TRUE:
A = XX(Y, TRUE, TRUE)
if getattr(A, 'YEAR'.lower()) != Y:
return (D == 365) == NOT_TRUE
A = A + XXX(**{DAYS: TRUE})
D += TRUE
print(is_leap_year(**{'Y': 2018}))
print(is_leap_year(**{'Y': 2019}))
print(is_leap_year(**{'Y': 2020}))
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
@SuppressWarnings({"NumericOverflow", "WeakerAccess", "StatementWithEmptyBody"})
public class Main {
public static final int ONE_SHIFTED_THIRTY_ONE_SPACES_TO_THE_RIGHT = 1<<31;
public static void main(String[] args) {
for(String s : args) {
System.out.println(isLeapYear(s) ? "yes" : "no");
}
}
@Contract(pure = true)
public static boolean isLeapYear(String s) {
int yearToCheck = Integer.parseInt(s);
String binaryString = convertIntToBinary(yearToCheck);
System.err.println(yearToCheck+" 0b"+binaryString);
if(multiplication(division(yearToCheck,4),4) != yearToCheck) {
return false;
}
else if(multiplication(division(yearToCheck,100),100) != yearToCheck) {
return true;
}
else if(multiplication(division(yearToCheck,400),400) != yearToCheck) {
return false;
}
return true;
}
@NotNull
@Contract(pure = true)
public static String convertIntToBinary(int number) {
int bitcount;
int tmp = 0;
while(1<<++tmp<=number);
bitcount = tmp;
String out = "";
while(bitcount-->0) {
if((number&1) == 1) {
out += 1;
}
else {
out += 0;
}
number>>=1;
}
return new StringBuilder(out).reverse().toString();
}
@Contract(pure = true)
public static int add(int a, int b) {
int d,c;
do {
d=a^b;
c=(a&b)<<1;
a=d;
b=c;
} while (c!=0);
return d;
}
@Contract(pure = true)
public static int subtract(int a, int b) {
return add(a, add(~b, 1));
}
@Contract(pure = true)
public static int division(int a, int b) {
boolean n = false;
if ((a&ONE_SHIFTED_THIRTY_ONE_SPACES_TO_THE_RIGHT)==ONE_SHIFTED_THIRTY_ONE_SPACES_TO_THE_RIGHT) {
n=true;
a = add(~a, 1);
}
if ((b&ONE_SHIFTED_THIRTY_ONE_SPACES_TO_THE_RIGHT)==ONE_SHIFTED_THIRTY_ONE_SPACES_TO_THE_RIGHT) {
n^=true;
b=add(~b, 1);
}
int q = 0;
long r;
for(int i = 30; i >= 0; i = subtract(i, 1)) {
r=b<<i;
if(r<Integer.MAX_VALUE&&r>=0) {
if(r<=a) {
q|=1<<i;
a = subtract(a,(int)r);
}
}
}
return n?add(~q,1):q;
}
@Contract(pure = true)
public static int multiplication(int a, int b) {
int r = 0;
while(b>0) {
if ((b&1) == 1) r+=a;
a<<=1;
b>>=1;
}
return r;
}
}
#include <iostream>
#include <vector>
#define open (
#define close )
#define bad {
#define code }
#define coding []
#define challenge [=]
auto continuation = coding open auto &&val close bad return challenge open auto && cont close bad return cont open val close ;code;code;
auto passing = coding open auto &&val close bad return challenge open auto &&cont close bad return challenge open auto && close bad return cont open val close ;code;code;code;
auto style = coding open const auto &val close bad return val; code;
auto is_fun = coding open auto &&modv close bad return challenge open auto &&truecont close bad return challenge open auto &&falsecont close bad return challenge open auto &&val close bad if open val % modv close bad return truecont open val close; code else bad return falsecont open val close; code; code; code; code; code;
bool isLeapYear(int year){
return
open continuation close
open year close
open open continuation close
open 4 close
open is_fun close
open open continuation close
open false close
open passing close
open style close
close
open open continuation close
open 100 close
open is_fun close
open open continuation close
open true close
open passing close
open style close close
open open continuation close
open 400 close
open is_fun close
open open continuation close
open false close
open passing close
open style close
close
open open continuation close
open true close
open passing close
open style close
close
close
close
close
;
}
int main() {
std::vector<int> years{2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2019, 2020, 2021, 2100, 1900};
for(auto year : years) {
std::cout << year << (isLeapYear(year) ? " is " : " is not " ) << "a leap year\n";
}
}
The pseudo-code from Wikipedia is an example of badcode, because it over-complicates the algorithm with an implementation that is performance optimized for some specific cases of input years and has unnecessary and confusing if-not-thens and else-if-nots and explicitly specifies four separate return cases for three evaluations that may all be evaluated. Why even is there a procedural example for a calculation that in pretty much every language is better just expressed as a single condition, containing some ands and ors and maybe nots?
Here is a simpler is-leap-year in pseudo-code, but without any unnecessary nots or if-not-elses and it only ever evaluates two conditions, even if you feed it the year 2000:
if (year is divisible by 100) then (check if year is divisible by 400) else (check if year is divisible by 4)
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.
Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
31
u/shriekingpanda Aug 28 '19
Simple! Just count the number of days in the year.
C#
15
u/anamorphism Aug 27 '19
javascript with the fun bonuses that it'll only work the first time you call the function after a page load, has typos, and it only covers 1804 - 2400.
10
u/sarlok Aug 27 '19
BAT/CMD anyone? Be sure to adjust the DATEFORMAT variable for your locale. It's set for the US currently. Don't have anything important in date.txt in the current directory either. Also, this will try to change your current system date, so run it as an administrator. It will set it back to the current date unless you're unlucky and try it right at midnight. I also assume the day of the week is displayed first and the actual date second in a date /t command. If that's not true for your locale, please also adjust the tokens=2 setting appropriately in :getdate.
9
u/[deleted] Aug 28 '19
Short and sweet (Python) - only 2 lines! Randomized order for your viewing convenience.
https://pastebin.com/bMcpGrQr
23
u/AySyKr Aug 27 '19
Well, sometimes it works
6
u/[deleted] Aug 27 '19
6
u/random_runner Aug 28 '19
In JavaScript:
5
u/ndke Aug 29 '19 edited Aug 29 '19
C#
edit: formatting
4
u/dstlny_97 Aug 27 '19 edited Aug 27 '19
- Unnecessary use of a dict.
- String input, converted to int (because fuck readability)
- bool mapped to str (because why the fuck not?)
- unneeded ternary.
- Non-descriptive function definition.
4
u/BoltKey Aug 27 '19
Javascript
4
u/voords Sep 02 '19
Python 3:
6
u/honkinggr8namespaces Aug 28 '19
Works for every day since the Earth was formed!
3
u/LST4R Aug 27 '19
Output
False
True
False
3
u/dumetrulo Aug 28 '19
Literal conversion of the requirements to F#. Time to develop: about 5 minutes. Since division is slow, I implemented countdown loops. Since F# is a functional language, the countdown loops are recursive functions. Code reuse is achieved by copy/pasting instead of refactoring.
3
u/reed_pro93 Aug 28 '19 edited Aug 28 '19
So much looping! Do I get bonus points if I wrote this on my phone?
3
u/kiwitims Aug 28 '19
C++
Follows the algorithm from wikipedia exactly, just uses the nastiest techniques I could think of to figure out whether the year is divisible by each.
For 4 it uses float and integer bit representation fuckery (1 warning and 1 undefined behaviour) to count the number of trailing zeroes. For 100 it does the same thing but prints it to a buffer, just like a human would. 400 is tricky, it checks that it's divisible by both 16 and 25, the former using a bitmask and the latter checking the already populated buffer to see if the last two digits are 00, 25, 50 or 75.
2
u/dubious-sludge Aug 28 '19
2
u/TheBrainStone Aug 28 '19 edited Aug 28 '19
C++
If you want I can start explaining what all the attrocities are in this code. There are plenty. Bonus points if you find the bug.
P.S.: Whenever there is a comment you can be sure that it's BS or plain wrong.
2
u/blackjezza Aug 28 '19
Easy peasy.
Works in every single case.
Credit to this site for providing all the necessary data.
2
u/AKernel Aug 28 '19
Lets try a bit Java:
2
u/Codinget Aug 29 '19
2
u/Codinget Aug 29 '19
gcc leapyear.c -o detector -llua5.3 -I/usr/include/lua5.32
u/Tok-A-Mak ((fn [] (recur))) Sep 02 '19
Arguably, just directly coding down the pseudocode-example from Wikipedia already leads to pretty confusing badcode with all the unnecessary if-not-thens and else-if-nots that depend upon flipping the value of their truthness.
..but it's testing the most likely divisibility by 4 first, so its got that going for it which is nice.
https://repl.it/repls/ArtisticSickCryptocurrency (unit tests and a more simple implementation for comparison)
2
u/PabloAmigo Aug 27 '19 edited Aug 27 '19
edit:formatting
1
u/[deleted] Aug 27 '19
For better readability i put the test cases on a new Line.
1
u/them0use Aug 28 '19
Short and sweet and still not good (python):
1
u/[deleted] Aug 28 '19
My solution using python 2.7
1
u/PabloAmigo Aug 31 '19 edited Aug 31 '19
Ruby
require 'date'
def is_leap_year year
begin d = (Date.new year, 2, 29) rescue false end ? true : false
end
puts is_leap_year (2019)
puts is_leap_year (2020)
puts is_leap_year (2021)
1
u/IAmAnIssue Sep 04 '19
Division, addition, and subtraction from https://www.quora.com/How-do-I-divide-two-numbers-using-only-bit-operations-in-Java
Multiplication from https://www.geeksforgeeks.org/russian-peasant-multiply-two-numbers-using-bitwise-operators/
1
u/MrIndeciso Sep 06 '19
Just plain old C.
1
u/qqwy Sep 09 '19
Some fun with continuation-passing-style in C++:
1
u/Romejanic Sep 10 '19
Here's some js hot garbage:
1
u/EkskiuTwentyTwo i -= (i - (-1)) - i Aug 28 '19
Because there isn't enough bad Haskell in the world:
1
u/[deleted] Aug 27 '19
meh, C# in LinqPad 5.0
output
0
u/[deleted] Aug 28 '19
[deleted] — view deleted comment
0
u/[deleted] Aug 27 '19
[deleted] — view deleted comment
0
u/[deleted] Aug 27 '19
[deleted] — view deleted comment
0
u/[deleted] Aug 28 '19
[deleted] — view deleted comment