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.
raise
.I’ll have to wait til Sunday to check the answers 😉
Answered by Stephen Universe on November 8, 2021
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
O
, 25 byteskðtD4/‟₀/N‟:400/kτṠ7%2<[←
Vyxal doesn't have a weekday function, so I made one myself.
Answered by emanresu A on November 8, 2021
-G
, 14 bytes>`date` dd Su*
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 outputdd
: "copy and convert" - here it basically does nothing
Su*
: search for a file starting with Su
dd
dd
expects no arguments, this produces an error-G
option: if no file matches (i.e. it is not Sunday), don't error as usualThis 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:
-G
, 18 bytes>`date` mv <-> Su*
<->
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
çKe ªUí
ç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
/1-6.d9
/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
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.
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.
1
by the MOD()
value or used +6
instead of -1
.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").FALSE
, because it errors or returns nothing.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
žg¦¦D4÷že+•YFóåι•žf<è+žg4Öžf3‹&-ŽPjžg2£4%è++7%iõEëõ}
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
Returns 1 on Mondays, 0 on other days, and throws an ArithmeticException on Sundays
v->1/new java.util.Date().getDay()
Answered by Benjamin Urquhart on November 8, 2021
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
${(%):-%(w._.)}
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
_=>{if(1/(int)DateTime.Now.DayOfWeek<0);}
Thanks to @caird coinheringaahing and @Jo King
Answered by SirTaphos on November 8, 2021
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
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
if(format(Sys.Date(),'%u')>6)a
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
#(and(=(.getDay(java.util.Date.))7)(/ 1 0))
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
(1:6)(weekday(now)-1);
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)
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
Answered by RandomOfAmbr on November 8, 2021
import Foundation;if(Calendar.current.component(.day,from:Date()))==7{exit(1)}
Answered by Zeke Snider on November 8, 2021
PS1='`((1/D{%w}))&&:`'
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
Answered by Brad Gilbert b2gills on November 8, 2021
END{1/strftime("%w")}
Saved 4 bytes thanks to manatwork
Saved 2 bytes thanks to mik
Answered by Noskcaj on November 8, 2021
Answered by Rɪᴋᴇʀ on November 8, 2021
Thanks to @Dennis for pointing out <
saves a byte over !=
.
@assert Dates.dayofweek(now())<7
Answered by gggg on November 8, 2021
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
f(n){n/=time(0)/86400%7^3;}
-7 bytes with thanks to @MartinEnder and @Dennis
Answered by Alnitak on November 8, 2021
Answered by Dennis on November 8, 2021
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 >
.
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
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
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
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
Answered by ATaco on November 8, 2021
%put %eval(1/(1-%index(&sysday,Su)))
Answered by J_Lard on November 8, 2021
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
Answered by Xcali on November 8, 2021
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.ǝ
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
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.
Answered by Engineer Toast on November 8, 2021
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
(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.
Answered by manatwork on November 8, 2021
<?@date(w)?:n;
Assumes default settings.
Output on Sundays
Fatal error: Undefined constant 'n' on line 1
Answered by primo on November 8, 2021
v->1/new java.util.Date().getDay()
-26 bytes thanks to @OlivierGrégoire.
-9 bytes thanks to @Neil.
Explanation:
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
Thanks to @Ken Y-N for saving 13 bytes!
#import<time.h>
f(n){time(&n);n/=gmtime(&n)->tm_wday;;}
Answered by Steadybox on November 8, 2021
@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
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");'
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
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
Answered by Uriel on November 8, 2021
stopifnot(weekdays(Sys.Date(),T)!="Sun")
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
import Data.Dates
succ.dateWeekDay<$>getCurrentDateTime
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.
import Data.Dates
main=pure$!succ.dateWeekDay<$>getCurrentDateTime
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.
Data.Time
: 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
l-6.d9
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
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
Date().slice(1)>'um'&&k
Full program.
The variable k
must not be defined.
/Su/.test(Date())&&k
Date().match`Su`&&k
Answered by l4m2 on November 8, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP