TransWikia.com

We had a question once which only failed on Sundays

Code Golf Asked by Manny Queen on November 8, 2021

Inspired by We had a unit test once which only failed on Sundays, write a program or function that does nothing but throw an error when it is Sunday, and exit gracefully on any other day.

Rules:

  • No using input or showing output through the usual IO methods, except to print to STDERR or your language’s equivalent. You are allowed to print to STDOUT if it’s a by-product of your error.
  • A function may return a value on non-Sundays as long as it doesn’t print anything
  • Your program may use a Sunday from any timezone, or the local timezone, as long as it is consistent.
  • An error is a something that makes the program terminate abnormally, such as a divide by zero error or using an uninitialised variable. This means that if any code were to be added after the part that errors, it would not be executed on Sunday.
  • You can also use statements that manually create an error, equivalent to Python’s raise.
  • This includes runtime errors, syntax errors and errors while compiling (good luck with that!)
  • On an error there must be some sign that distinguishes it from having no error
  • This is , so the shortest bytecount in each language wins!

I’ll have to wait til Sunday to check the answers 😉

52 Answers

Python 3, 50 bytes

from datetime import*
1/(date.today().weekday()-6)

Try it online!

Answered by Stephen Universe on November 8, 2021

TI-Basic, 22 21 bytes

getDate
log(log(dayOfWk(Ans(1),Ans(2),Ans(3

-1 byte by using MarcMush's method but replacing ln( with log(.

Only works on TI-84+/SE. Assumes that the date is set correctly before the program is run. There is a newline at the end.

Answered by Yousername on November 8, 2021

Vyxal O, 25 bytes

kðtD4/‟₀/N‟:400/kτṠ7%2<[←

Try it Online!

Vyxal doesn't have a weekday function, so I made one myself.

Answered by emanresu A on November 8, 2021

Zsh -G, 14 bytes

>`date`
dd Su*

Attempt This Online!

  • date: get the date in the format Sun 28 Mar 07:55:54 BST 2021
  • >: create a file named according to each of the words in the output
  • dd: "copy and convert" - here it basically does nothing
    • this command expects no arguments
  • Su*: search for a file starting with Su
    • if a file matching that exists (which happens when it is Sunday), then it is passed to dd
      • since dd expects no arguments, this produces an error
    • with the -G option: if no file matches (i.e. it is not Sunday), don't error as usual

This produces a bit of extra junk output to STDERR (not an error though) which may or may not be allowed; the question isn't really clear. Here's an alternative answer which doesn't:

Zsh -G, 18 bytes

>`date`
mv <-> Su*

Attempt This Online!

<-> matches any file whose name is a number, of which there are two: the day of the month, and the year.

When there is no Su* file, this is renames the day of the month to the year (overwriting the year), which works fine.

When Sun exists, it tries to move the day of the month and the year into the directory Sun, which fails because Sun is a file, not a directory.

Answered by pxeger on November 8, 2021

Japt, 7 bytes

çKe ªUí

Test it

çKe ªUí
ç           :U=0 times repeat
 K          :  Current date
  e         :  0-based day of the week
    ª       :  Logical OR with
     Uí     :  The result of running the í method on U, which doesn't exist for numbers

Answered by Shaggy on November 8, 2021

Pyth, 7 bytes

/1-6.d9

Try it online!

/1-6.d9
    .d9  // Current day of the week, 0 indexed on monday.
  -6     // 6 - day of week (0 if Sunday)
/1       // 1 ÷ ^

Answered by Scott on November 8, 2021

Excel, 24

Closing quote and paren not counted toward final score, as Excel will autocorrect both of those. Tested in Excel 2016.

=IF(MOD(TODAY()-1,7)^0,"")

I think this is different from the other submission enough to warrant another answer.

How it works:

  • I've rolled the error into the conditional check. As it turns out, TODAY() mod 7 also gives the weekday. If it's a Sunday, this means that MOD(TODAY()-1,7) is 0, and 0^0 is an error in Excel.
    • Of course, I could also have divided 1 by the MOD() value or used +6 instead of -1.
  • If it's not Sunday, the MOD(...,7) will be non-zero, which when raised to 0, returns 1, a truthy value. This makes the IF return an empty string (our "nothing").
  • The if statement, therefore, cannot evaluate to FALSE, because it errors or returns nothing.

Alternative

Here's one that works just as well, but uses a Name error instead:

=IF(MOD(TODAY(),7)=1,A,"")

Answered by Calculuswhiz on November 8, 2021

05AB1E, 54 52 bytes

žg¦¦D4÷že+•YFóåι•žf<è+žg4Öžf3‹&-ŽPjžg2£4%è++7%iõEëõ}

Try it online!

Explanation

Formula from here.

žg¦¦                                                 # Take the last two digits of the year.
    D                                                # Save for later.
     4÷                                              # Divide by 4, discarding any fraction.
       že+                                           # Add the day of the month.
          •YFóåι•                                    # Push the month's key values.
                 žf                                  # Take the month.
                   <è                                # Find the month's key value.
                     +                               # Add the month's key value.
                      žg4Ö                           # Is this year a leap year?
                          žf3‹                       # Is it January or Feburary?
                              &                      # And the results of both questions.
                               -                     # Subtract 1 for January or February of a leap year.
                                ŽPj                  # Push 6420.
                                   žg2£              # Take the first two digits of the year.
                                       4%è           # Index the thing into the list.
                                          +          # Do step 6.
                                           +         # Add the last two digits of the year.
                                            7%       # Divide by 7 and take the remainder.
                                              i  ë } # Sunday is 1, so it goes in the if.
                                              iõ ë } # Push empty string.
                                              i Eë } # For loop.
                                              i  ëõ} # If not sunday, push empty string and implicit output.

Answered by PkmnQ on November 8, 2021

Java 8, 34 bytes

Returns 1 on Mondays, 0 on other days, and throws an ArithmeticException on Sundays

v->1/new java.util.Date().getDay()

Try it online!

Answered by Benjamin Urquhart on November 8, 2021

SmileBASIC, 20 bytes

DTREAD OUT,,,W
W=W/W

DTREAD outputs the current year, month, day, and day of the week. Sunday is 0.

Answered by 12Me21 on November 8, 2021

Zsh, 15 bytes

${(%):-%(w._.)}

Try it online!

Prompt sequences can be really crazy sometimes...

${(%):-%(w._.)}
${(%)         }   # expand as prompt sequence
     :-           # ${var:-fallback}, but without the var
       %( . .)    # Prompt ternary
         w        # If DoW matches given number (implied 0, which is Sunday)
          ._      # Then substitute _
            .     # Else substitute nothing

Since _ is not a command, it fails on Sunday.

Answered by GammaFunction on November 8, 2021

Postgresql, 32

Not sure if you need to add ; at the end for valid answer

SELECT 1/EXTRACT(DOW FROM now())

Answered by dwana on November 8, 2021

C# (.NET Core), 39 43 41 bytes

_=>{if(1/(int)DateTime.Now.DayOfWeek<0);}

Try it online!

Thanks to @caird coinheringaahing and @Jo King

Answered by SirTaphos on November 8, 2021

Excel, 77 30 bytes

Yes, vastly more golfable.

=IF(WEEKDAY(TODAY())=1,1/0,"")

Simply checks if it's Sunday, and if so, finds the quickest way I know of to error. If not Sunday, returns "",the closest Excel has to not returning anything

Answered by Scott on November 8, 2021

VBA 18 bytes

This relies on the inbuilt function date() returning a day number that remainders 1 if divided by 7, so may be OS and/or CPU specific.

a=1/(date mod 7-1)

It runs in the VBA project Immediate window.

Answered by JohnRC on November 8, 2021

R, 31 bytes 30 bytes

if(format(Sys.Date(),'%u')>6)a

Try it online!

No output on non-Sundays, Error: object 'a' not found on Sundays.

format(Sys.Date(),'%u') was the shortest way I could find to get weekday, it outputs a character-class number for day of week, with 7 for Sundays. We can compare to a numeric 7, and if true attempt to use an undefined object.

Saved a byte thanks to Giuseppe!

Answered by Gregor Thomas on November 8, 2021

Clojure, 43 bytes

#(and(=(.getDay(java.util.Date.))7)(/ 1 0))

Try it online!

Uses the fact that and doesn't evaluate the second argument unless necessary. I originally thought I could get away with using the Ratio literal 1/0 to save two bytes, but that unfortunately causes exceptions immediately. It must try to reduce the Ratio right away or something.

(defn sunday-fail []
  (and (= (.getDay (Date.)) 7)
       (/ 1 0)))

Answered by Carcigenicate on November 8, 2021

Octave, 23 22 bytes

(1:6)(weekday(now)-1);

Try it online!

This will try to access an element in 1:6. When the day is Sunday it will try to access the element (1-1)=(0) which will result in an error as MATLAB is 1-indexed.


Original for 23.

assert(weekday(now)~=1)

Try it online!

assert(...) will throw an error when the condition is false. weekday(now) returns the current day of the week where 1 = Sunday. Put the two together, the code will throw an error only on sundays when the condition becomes 1~=1.

Answered by Tom Carpenter on November 8, 2021

Groovy, 16 bytes

1/new Date().day

Try it online!

Answered by RandomOfAmbr on November 8, 2021

Swift 4, 78 bytes

import Foundation;if(Calendar.current.component(.day,from:Date()))==7{exit(1)}

Try it online!

Answered by Zeke Snider on November 8, 2021

Pure bash BASH (interactive mode + no coreutils required), 17 20 19 bytes

PS1='`((1/D{%w}))&&:`'

Now only 19 bytes thanks to manatwork's comment below.

Bonus, if you put it in your bashrc it fails every sunday you log in :-) not just when you run it on sundays!

Answered by Ahmed Masud on November 8, 2021

Perl 6,  29  21 bytes

die if now.Date.day-of-week>6

Try it

die if now/86400%7+^3

Try it

Answered by Brad Gilbert b2gills on November 8, 2021

AWK, 27 25 23 21 bytes

END{1/strftime("%w")}

Try it online!

Saved 4 bytes thanks to manatwork

Saved 2 bytes thanks to mik

Answered by Noskcaj on November 8, 2021

Julia 0.5, 28 bytes

Dates.dayofweek(now())<7||~-

Try it online!

This does not work with 0.6, but it does with 0.4.

Answered by Rɪᴋᴇʀ on November 8, 2021

Julia 0.6, 32 bytes

Thanks to @Dennis for pointing out < saves a byte over !=.

@assert Dates.dayofweek(now())<7

Try it online!

Answered by gggg on November 8, 2021

Q, 20 Bytes

if[1=.z.d mod 7;'e]

.z.d returns the current date. mod does the modulo of the current date, which returns an int. If the date is a sunday, .z.d mod 7 returns 1. If 1=1, (on sunday), and error is raised using the ' operator For brevity the error is just the e character.

Answered by tkg on November 8, 2021

C, 35, 34 27 bytes

f(n){n/=time(0)/86400%7^3;}

-7 bytes with thanks to @MartinEnder and @Dennis

Try it online!

Answered by Alnitak on November 8, 2021

Bash + coreutils, 15 14 bytes

`date|grep Su`

Try it online!

Answered by Dennis on November 8, 2021

MATL, 12 bytes

vZ'8XOs309>)

The error produced on Sundays is:

  • Interpreter running on Octave:

    MATL run-time error: The following Octave error refers to statement number 9:  )
    ---
    array(1): out of bound 0
    
  • Interpreter running on Matlab:

    MATL run-time error: The following MATLAB error refers to statement number 9:  )
    ---
    Index exceeds matrix dimensions
    

To invert behaviour (error on any day except on Sundays), add ~ after >.

Try it Online!

Explanation

This exploits the fact that

  • indexing into an empty array with the logical index false is valid (and the result is an empty array, which produces no output); whereas

  • indexing with true causes an error because the array lacks a first entry.

Commented code:

v       % Concatenate stack. Gives empty array
Z'      % Push current date and time as a number
8XO     % Convert to date string with format 8: gives 'Mon', 'Tue' etc
s       % Sum of ASCII codes. Gives 310 for 'Sun', and less for others
309>    % Greater than 309? Gives true for 'Sun', false for others
)       % Index into the empty array
        % Implicit display. Empty arrays are not displayed (not even newline)

Answered by Luis Mendo on November 8, 2021

PowerShell, 24 20 Bytes

1/(date).DayOfWeek>1

Sunday triggers divide by zero same as most of the other solution here. Problem is that on other days that a double gets returned so redirect to nowhere useful trumps that output.

Answered by Matt on November 8, 2021

TI-Basic 84+, 23 bytes

getDate
0/(1-dayOfWk(Ans(1),Ans(2),Ans(3

Needs date & time commands, which are 84+ and higher only.

Answered by Timtech on November 8, 2021

Funky, 21 bytes

if!os.date"%w"error()

os.date"%w" returns the current day of the week in 0-6 format, where 0 is sunday. Getting the logical not of that is only true when the weekday is 0, so Sunday. Then just a basic if(a){error()} will assure that this program only errors on sunday

Try it online!

Answered by ATaco on November 8, 2021

SAS, 36 bytes

%put %eval(1/(1-%index(&sysday,Su)))

Answered by J_Lard on November 8, 2021

Ocaml, 46 bytes

open Unix
let()=1/(gmtime(time())).tm_wday;()

and in the ocaml REPL, we can achieve better by removing the let and the final :():

$ open Unix;;1/(gmtime(time())).tm_wday;;<CR>

which is 41 bytes (incuding 1 byte for the carriage return).

Answered by Bromind on November 8, 2021

Perl 5, 13 bytes

1/(gmtime)[6]

Try it online!

Ported @biketire's answerj

removed 3 bytes with @mik's reminder

Answered by Xcali on November 8, 2021

05AB1E, 45 44 bytes

As 05AB1E doesn't have a built in for getting the day of the week, I've used Zeller's Rule to calculate it.

Prints a newline to stderr in case of a Sunday (observable in the debug view on TIO)

žežf11+14%Ì13*5÷žgžf3‹-т%D4÷žgт÷©4÷®·(O7%i.ǝ

Try it online!

Explanation

The general formula used is
DoW = d + [(13*(m+1))/5] + y + [y/4] + [c/4] - 2*c
Where DoW=day of week, d=day, m=month, y=last 2 digits of year, c=century and and expression in brackets ([]) is rounded down.

Each month used in the formula correspond to a number, where Jan=13,Feb=14,Mar=3,...,Dec=12
As we have the current month in the more common format Jan=1,...,Dec=12 we convert the month using the formula
m = (m0 + 11) % 14 + 1

As a biproduct of March being the first month, January and February belong to the previous year, so the calculation for determining y becomes
y = (year - (m0 < 3)) % 100

The final value for DoW we get is an int where 0=Sat,1=Sun,...,6=Fri.
Now we can explicitly throw an error if the result is true.

Answered by Emigna on November 8, 2021

VBA / VBScript, 22 20 bytes

Saved 2 bytes thanks to Taylor Scott.

a=1/(Weekday(Now)-1)

This should be run in the Immediate Window. Weekday() returns 1 (Sunday) through 7 (Saturday) so this creates a divide by zero error on Sunday. Otherwise, no output.

Error Message

Answered by Engineer Toast on November 8, 2021

Ruby, 15 bytes

1/Time.now.wday

wday will return 0 on Sunday causing a ZeroDivisionError: divided by 0 error. For example: 1/Time.new(2018,1,7).wday.

Answered by Biketire on November 8, 2021

jq, 42 characters

(39 characters code + 3 characters command line option)

now|strftime("%w")|strptime("%d")|empty

Just trying a different approach here: parse week day number (0..6) as month day number (1..31).

Sample run:

bash-4.4$ TZ=UTC faketime 2018-01-06 jq -n 'now|strftime("%w")|strptime("%d")|empty'

bash-4.4$ TZ=UTC faketime 2018-01-07 jq -n 'now|strftime("%w")|strptime("%d")|empty'
jq: error (at <unknown>): date "0" does not match format "%d"

Note that jq only handles UTC dates.

Try it online!

Answered by manatwork on November 8, 2021

PHP, 15 bytes

<?@date(w)?:n;

Assumes default settings.

Output on Sundays

Fatal error: Undefined constant 'n' on line 1

Try it online!

Answered by primo on November 8, 2021

Java 8, 69 43 34 bytes

v->1/new java.util.Date().getDay()

-26 bytes thanks to @OlivierGrégoire.
-9 bytes thanks to @Neil.

Explanation:

Try it here.

  • v->{...} (unused Void null parameter) is one byte shorter than ()->{...} (no parameter).
  • new java.util.Date().getDay() will return 0-6 for Sunday-Saturday, so 1/... will give an java.lang.ArithmeticException: / by zero error if the value is 0, which only happens on Sundays.

Answered by Kevin Cruijssen on November 8, 2021

C,  68  55 bytes

Thanks to @Ken Y-N for saving 13 bytes!

#import<time.h>
f(n){time(&n);n/=gmtime(&n)->tm_wday;;}

Try it online!

Answered by Steadybox on November 8, 2021

Batch, 88 bytes

@for /f "skip=1" %%d in ('wmic path win32_localtime get dayofweek')do @set/a1/%%d&exit/b

Tries to divide by zero on Sunday.

Unfortunately neither date nor powershell date work on my PC to give me the day of the week.

Answered by Neil on November 8, 2021

PHP 7, 12 bytes

1%date("w");

On PHP 7 it throws an exception of type DivisionByZero on Sundays. The same happens if it is interpreted using HHVM.

On PHP 5 it displays a warning (on stderr) on Sundays:

PHP Warning:  Division by zero in Command line code on line 1

On any PHP version, it doesn't display anything on the other days of the week.

Run using the CLI:

php -r '1%date("w");'

or try it online!

Two more bytes can be squeezed by stripping the quotes (1%date(w);) but this triggers a notice (that can be suppressed by properly set error_reporting = E_ALL & ~E_NOTICE in php.ini).

Answered by axiac on November 8, 2021

Gema, 40 characters

A=@subst{Su=@err{S};*=;@datime}@end

Had to specify an error message, so choose a short one: “S”.

Sample run:

bash-4.4$ faketime 2018-01-06 gema 'A=@subst{Su=@err{S};*=;@datime}@end'

bash-4.4$ faketime 2018-01-07 gema 'A=@subst{Su=@err{S};*=;@datime}@end'
S

Answered by manatwork on November 8, 2021

APL (Dyalog), 23 bytes

⎕CY'dfns'
o←÷7|⌊days⎕TS

Try it online!

Answered by Uriel on November 8, 2021

R, 40 bytes

stopifnot(weekdays(Sys.Date(),T)!="Sun")

Try it online!

weekdays returns the weekday of the date, with an optional argument abbreviate, which shortens Sunday to Sun, saving a single byte.

stopifnot throws an error if, for each argument, not all are TRUE, and throws an error with a message indicating the first element of which isn't TRUE, so the error is Error: "Sun" is not TRUE

Answered by Giuseppe on November 8, 2021

Haskell + Data.Dates, 55 bytes

import Data.Dates
succ.dateWeekDay<$>getCurrentDateTime

Try it online!

This uses the fact that Sunday is the last day of the week. dateWeekDay returns the day of the week as a WeekDay type, which is simply defined as

data WeekDay = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday

WeekDay is an instance of Enum, thus we can use succ and pred to get the successor or predecessor of a weekday, e.g. succ Monday yields Tuesday.

However, Sunday is the last enum entry, so calling succ Sunday results in the following error:

fail_on_sunday.hs: succ{WeekDay}: tried to take `succ' of last tag in enumeration
CallStack (from HasCallStack):
  error, called at .DataDates.hs:56:34 in dates-0.2.2.1-6YwCvjmBci55IfacFLnAPe:Data.Dates

Edit 1: Thanks to nimi for -3 bytes!
Edit 2: -11 bytes now that functions are allowed.


Full program: 88 81 74 69 66 bytes

import Data.Dates
main=pure$!succ.dateWeekDay<$>getCurrentDateTime

Try it online!

pure is needed to lift the resulting WeekDay back into the IO Monad. However, Haskell sees that the value is not output in any way by the program, so lazy as it is, the expression is not evaluated, so even on Sundays the program would not fail. This is why $! is needed, which forces the evaluation even if Haskell would normally not evaluate the expression.


Previous approach with Data.Time: 127 124 bytes

import Data.Time.Clock
import Data.Time.Calendar.WeekDate
c(_,_,d)|d<7=d
main=getCurrentTime>>=(pure$!).c.toWeekDate.utctDay

Try it online! These are some impressive imports. Change d<7 to e.g. d/=5 to test failure on a Friday. Fails with the following exception: Non-exhaustive patterns in function c.

Answered by Laikoni on November 8, 2021

Pyth, 8 7 bytes

 l-6.d9

Try it online!

Explanation

    .d9 # Get the current day of week (0 = Monday, 6 = Sunday)
  -6    # Subtract 6 from the day
 l      # Try to calculate the log base 2 of the result of the previous operation raising a "ValueError: math domain error" on sundays
        # there is an extra space at the start, to supress the output on the other days

Answered by Rod on November 8, 2021

C# (.NET Core), 55 54 48 bytes

Try it online!

Saved 1 byte thanks to Shaggy

Saved 5 byte thanks to Emigna

Saved 1 byte thanks to Kevin Cruijssen

_=>{var k=1/(int)System.DateTime.Now.DayOfWeek;}

Lucky that Sunday is indexed 0 in enum or else it would've needed to be (System.DayOfWeek)7

Answered by LiefdeWen on November 8, 2021

JavaScript, 23 Bytes

Date().slice(1)>'um'&&k

Full program.

The variable k must not be defined.

JavaScript, 20 bytes by Rick Hitchcock

/Su/.test(Date())&&k

JavaScript, 19 bytes by apsillers

Date().match`Su`&&k

Answered by l4m2 on November 8, 2021

Python 3, 33 bytes

import time
"Su"in time.ctime()>q

Try it online!

Python 3, 50 bytes

from datetime import*
datetime.now().weekday()>5>q

Try it online!

Saved ~3 bytes thanks to Rod.

Answered by Mr. Xcoder on November 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP