2
$\begingroup$

I am solving a certain challenge given by my friend.

I want to print the first day of the year if it is not a leap year, while I want both first and second days if it is a leap year.

I want to know if there is an efficient way to rewrite this piece of code:

If[Mod[year,4]==0,DayName/@{{year,1,1},{year,1,2}},{DayName[{year,1,1}]}]
$\endgroup$
  • 1
    $\begingroup$ As an aside: leap years are not years which are multiples of 4, the definition is slightly more complex $\endgroup$ – Lonidard Dec 3 '18 at 22:27
4
$\begingroup$

Here is an alternate solution not using If:

Table[ DayName[ {year, 1, x} ], {x, 1 + Boole[ LeapYearQ[{year} ]]} ]
|improve this answer|||||
$\endgroup$
2
$\begingroup$

LeapYearQ should be more reliable, in particular since special rules apply if the year is divisible by 100 or 400.

f = year \[Function] If[
   LeapYearQ[{year, 1, 1}],
   DayName /@ {{year, 1, 1}, {year, 1, 2}},
   {DayName[{year, 1, 1}]}
   ]
|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thanks for that tip. But is there still a better way to write the rest of the code? I mean specifically for DayName part. $\endgroup$ – exp ikx Dec 3 '18 at 20:12
  • $\begingroup$ Hm. What does "better" mean? Are you concerned about efficiency? Why? How many years do you want to test this way? $\endgroup$ – Henrik Schumacher Dec 3 '18 at 20:14
  • $\begingroup$ I'm concerned about efficiency since it's a challenge. Nothing much. $\endgroup$ – exp ikx Dec 3 '18 at 20:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.