8
\$\begingroup\$

Not restricted to any one programming language.

What I'm saying is you pass 1 to it and it returns Monday, 7 corresponds with sunday and so on.

I've managed a 146 byte statement in Java to do the same.

return (n<1?"invalid":(n<2?"monday":(n<3?"tuesday":(n<4?"wednesday":(n<5?"thursday":(n<6?"friday":(n<7?"saturday":(n<8?"sunday":"invalid"))))))));

Your program should:

  • output full words (STDOUT)
  • not crash if the input is less than 1 or greater than 7
\$\endgroup\$
  • 6
    \$\begingroup\$ I can't know what other people are downvoting for, but I would expect people to dislike the use of "popularity contest" on a question that is purely a golf question. Generally popularity contest is used for questions that don't have an objective way of deciding a winner. \$\endgroup\$ – trichoplax Aug 15 '14 at 15:25
  • 9
    \$\begingroup\$ This question can't agree with itself on what it wants people to write. A statement which finds input in a variable and returns it or a program which writes to stdout? (It's also a bizarre use of popularity-contest which, if it catches on, might do a lot to help those who want to kill the tag completely). \$\endgroup\$ – Peter Taylor Aug 15 '14 at 15:31
  • 2
    \$\begingroup\$ You'll learn what works and what makes a good question by asking questions just like you are, and getting feedback. I personally thought this question was too simple to make an interesting challenge, but you have 3 answers already in just half an hour, which shows that it's hard to guess what makes a good challenge until you ask it. With the new reputation you gain from this question you'll soon be able to use the sandbox to get feedback on ideas before you post them. \$\endgroup\$ – trichoplax Aug 15 '14 at 15:32
  • 2
    \$\begingroup\$ Note that questions are language agnostic by default - you don't need to specify that it's not restricted to one programming language. \$\endgroup\$ – trichoplax Aug 15 '14 at 15:35
  • 2
    \$\begingroup\$ The question says you should output to stdout, but the accepted answer doesn't do so and even assumes the existence of a variable. Also, do we have to output invalid if the input is invalid? The question doesn't state that but the example suggests so. \$\endgroup\$ – nyuszika7h Aug 17 '14 at 15:07

45 Answers 45

8
\$\begingroup\$

Ruby, 69 or 38 bytes

Here is a simple way to improve your code (written in Ruby but it works similarly in Java):

n>0&&n<8?%w{Mon Tues Wednes Thurs Fri Satur Sun}[n-1]+"day":"Invalid"
  • Combine the two invalid checks into one.
  • Put all the days in an array and use n as an index.
  • Factor out the common day.

You can make it even shorter if you import the names of the days of the week from a library, like Ruby's:

n>0&&n<8?Date::DAYNAMES[n%7]:"Invalid"

Note that now I don't decrement n but instead take it modulo 7 to map 7 to 0. This is because DAYNAMES starts with Sunday.

\$\endgroup\$
  • \$\begingroup\$ Gah, I was just about to put a Lua version of this same thing (except it was going to be about 100 characters longer)... \$\endgroup\$ – Kyle Kanos Aug 15 '14 at 15:22
  • \$\begingroup\$ damn, I wasn't thinking on the lines of arrays at all. I had gotten so caught up in ternary, that I hadn't realized I could merge the two. amazing! \$\endgroup\$ – CrazyMod Aug 15 '14 at 15:25
  • \$\begingroup\$ Can you do n>0&n<8 (removing the second &) in Ruby? I know that works in Java. \$\endgroup\$ – bmarks Aug 15 '14 at 15:51
  • \$\begingroup\$ @bmarks It looks like you can't due it due to precedence, at least before Ruby 2.0 (I don't have a Ruby 2.x interpreter here right now). \$\endgroup\$ – Martin Ender Aug 15 '14 at 15:54
  • 1
    \$\begingroup\$ 21 in Rebmu ... :-) \$\endgroup\$ – Dr. Rebmu Aug 18 '14 at 0:33
9
\$\begingroup\$

Bash: 47 bytes

Still no bash entry? I'm disappointed ...

case $1 in
    [1-7]) date -d "14-08-1$1" +%A
esac

It uses the days of the current week and simply substitutes the last digit (11-17 August 2014 -- 11 is Monday, 12 is Tuesday, etc.).

\$\endgroup\$
  • \$\begingroup\$ Wow, what a clever solution! Hard coding a date for this is brilliant!. Is there no way for the date format to accept just '8' as the month? And then you can find a month/year pair where the first is a monday. \$\endgroup\$ – Cruncher Aug 15 '14 at 18:52
  • \$\begingroup\$ Thanks! date -d $1sept +%A works as well (though only this year; reduces bytes to 6*9). GNU date is really flexible in that matter so there should be additional possibilities. \$\endgroup\$ – yasen Aug 15 '14 at 19:26
  • \$\begingroup\$ If you post this as an answer for date rather than Bash, it would be a mere 14-08-1$1 – 9 bytes! \$\endgroup\$ – Ingo Bürk Aug 15 '14 at 22:45
  • \$\begingroup\$ It's 46 bytes, don't count the trailing newline; \$\endgroup\$ – nyuszika7h Aug 17 '14 at 10:50
  • \$\begingroup\$ Well, more than 2 times shorter version :): codegolf.stackexchange.com/a/36424/11887 . \$\endgroup\$ – avall Aug 19 '14 at 13:18
6
\$\begingroup\$

Marbelous 192 191 185 181

}0
=1=2=3=4=5=6=7--
&1&2&3&4&5&6&7{0
&8////////////
4D6F6E547565735765646E65735468757273467269536174757253756E646179
&1&1&1&2&2&2&2&3&3&3&3&3&3&4&4&4&4&4&5&5&5&6&6&6&6&6&7&7&7&8&8&8

Non-zero exit code if the input is invalid

Usage:

# marbelous.py -r day-of-week.mbl 2
Tuesday
\$\endgroup\$
6
\$\begingroup\$

Javascript, 95 88 bytes

x=prompt();alert("Invalid 0Mon0Tue0Wednes0Thurs0Fri0Satur0Sun".split(0)[x&~7?0:x]+"day")

7 in binary is 0111, meaning that you can shave off a few characters with a bitwise operation instead of x>0&&x<8.

Edit: Removed the s array with the help of edc65.

\$\endgroup\$
  • \$\begingroup\$ that's a neat method! \$\endgroup\$ – CrazyMod Aug 15 '14 at 15:28
  • 1
    \$\begingroup\$ Neat method indeed. 1) I count 95 bytes, not 97. 2) You don't need ad s variable and can do 88:x=prompt();alert("Invalid 0Mon0Tue0Wednes0Thurs0Fri0Satur0Sun".split(0)[x&~7?0:x]+"day") \$\endgroup\$ – edc65 Aug 15 '14 at 21:41
  • \$\begingroup\$ Ah, that's clever! I'll update my post now. \$\endgroup\$ – Sean Latham Aug 17 '14 at 22:01
5
\$\begingroup\$

C# - 26 Bytes

Expects the day to be stored inside n.
Does not crash, as expected.
Powered by LINQPad™

((DayOfWeek)(n%7)).Dump();

Special thanks to bmarks and Stephan Schinkel for byte saving and rule bending, respectively

\$\endgroup\$
  • \$\begingroup\$ Can you remove the second & in the conditional? I don't think short circuit evaluation here is necessary. \$\endgroup\$ – bmarks Aug 15 '14 at 17:21
  • \$\begingroup\$ @bmarks You're correct, thanks \$\endgroup\$ – William Barbosa Aug 15 '14 at 17:23
  • 1
    \$\begingroup\$ The Question does not mentione to return "Invalid" it just states the program should not crash. So you could write return ((DayOfWeek)(i%7)).ToString(); (37 chars) \$\endgroup\$ – Stephan Schinkel Aug 21 '14 at 11:10
  • \$\begingroup\$ @StephanSchinkel Yeah, I guess you're right \$\endgroup\$ – William Barbosa Aug 21 '14 at 11:35
2
\$\begingroup\$

C#, 95 bytes

In C# you can do something like this:

return(i>7||i<0)?"invalid":new[]{"mon","tues","wednes","thurs","fri","satur","sun"}[i-1]+"day";
\$\endgroup\$
  • \$\begingroup\$ There is an error in the bounds checking, you need to be checking that i<1, and you can save 2 bytes by using | rather than || (not short-circuiting) and removing the brackets around the condition. It's also shorter to create and split a string thus " mon tues wednes thurs fri satur sun".Split()[i] than to create an array of string of this size (note the space at the start of the string, which saves subtracting 1 from i) \$\endgroup\$ – VisualMelon Aug 15 '14 at 16:01
2
\$\begingroup\$

Extended BrainFuck: 104

{a))<(->>}+>,49-(-(-(-(-(-((-)<->>|"sun")<(->>|"satur"&a|"fri"&a|"thurs"&a|"wednes"&a|"tues"&a|"mon")|"day"

Ungolfed (Idiomatic)

{main 
  :flag +
  :input

  $input &read_number -
  (-
   (-
    (-
     (-
      (-
       (        $input &reset  ; 7-9
                $flag  &reset
                |"sun" &reset )

        $flag ( &reset         ; 6 
                |"satur" &reset  ))

       $flag (  &reset         ; 5
                |"fri" &reset    ))

      $flag (   &reset         ; 4
                |"thurs" &reset  ))

     $flag (    &reset         ; 3
                |"wednes" &reset ))

    $flag (     &reset         ; 2
                |"tues" &reset   ))

   $flag (      &reset         ; 1
                |"mon" &reset    )

   |"day"
}
{reset (-)}
{read_number , 48- }

;; call main
&main
\$\endgroup\$
2
\$\begingroup\$

T-SQL 36

SELECT DATENAME(w,@+6)WHERE(6+@)/7=1

Assumes the variable is stored in @. If it is an invalid input (@>7 or @<1), then it doesn't select anything.

Edit: Apparently a date can be a number. Removed 5 characters with that.

Edit 2: Based on the first edit. Since it's an int, I don't have to use DATEADD(); I can use normal addition instead.

\$\endgroup\$
2
\$\begingroup\$

Javascript 93 :(

q=prompt();alert(q<8&&q>0?'0mon0tues0wednes0thurs0fri0satur0sun'.split(0)[q]+'day':'invalid')
\$\endgroup\$
  • \$\begingroup\$ why exactly have you used q&&q<8 ? \$\endgroup\$ – CrazyMod Aug 15 '14 at 15:32
  • \$\begingroup\$ q&&qq<8 checks if q is between 1 and 7 \$\endgroup\$ – Kevin L Aug 15 '14 at 15:33
  • 1
    \$\begingroup\$ What if q is -5? \$\endgroup\$ – Doorknob Aug 15 '14 at 15:42
  • \$\begingroup\$ :( but thats an extra 2 bytes for >0. Fixed using ipi's bit trick, also saves 2 bytes \$\endgroup\$ – Kevin L Aug 15 '14 at 15:46
  • \$\begingroup\$ Does it work with q == 0? \$\endgroup\$ – edc65 Aug 15 '14 at 21:23
2
\$\begingroup\$

Lua - 57 bytes

print(n>0 and n<8 and os.date("%A",9e4*(n+3))or"Invalid")

Lua has os.date() in it's standard library, and it has formatting. So you can pass a time (in this case "9e4*(n+3)") and ask to return the "%A" format, which is the names of the days of the week. Also, very useful in Lua is "a and b or c". If a is true (in the code a is "n>0 and n<8") it returns b, if a is false (or nil) it returns c.

\$\endgroup\$
  • 1
    \$\begingroup\$ Can you provide an explanation? \$\endgroup\$ – Cruncher Aug 15 '14 at 18:53
  • 1
    \$\begingroup\$ The OP specifically asked for error handling, although it was pretty vague. Next time, ask for clarification before posting an incomplete answer. \$\endgroup\$ – Rainbolt Aug 15 '14 at 19:23
  • 1
    \$\begingroup\$ I don't think the space after %A is necessary \$\endgroup\$ – Kyle Kanos Aug 16 '14 at 0:48
  • \$\begingroup\$ @KyleKanos Right you are. Thanks! \$\endgroup\$ – AndoDaan Aug 16 '14 at 1:40
2
\$\begingroup\$

Mathematica 19 16 bytes

DayName@{1,1,#}&

As Dr. Rebmu noted, January 1, 1 A.D. is a good place to start. It (presumably) fell on a Monday.

    DayName@{2014, 9, #} &[1]

Monday

\$\endgroup\$
  • \$\begingroup\$ Why September of 2014 and not January 1st year 1 AD? \$\endgroup\$ – Dr. Rebmu Aug 17 '14 at 18:52
  • \$\begingroup\$ The answer is: I failed to think of it. But I will incorporate your suggestion. \$\endgroup\$ – DavidC Aug 19 '14 at 11:16
2
\$\begingroup\$

Bash - 21 19

Assuming the input is in variable D:

date +%A -d$D"Jan1"

HTML + PHP - 26

Let $d be an input text

<?=date('l',86400*(3+$d));

Timestamp 86400*3 is the first Sunday from the start of UNIX world.

You can test it by executing:

<?php $d=3; ?>
<?=date('l',86400*(3+$d));
\$\endgroup\$
1
\$\begingroup\$

Perl, 60 bytes

Something like this:

$x&&qw{Mon Tues Wednes Thurs Fri Satur Sun}[$x-1]."day"||die

If want to return a message instead and you're concerned about negative indexes you can use this one instead (8 more chars):

$x>0&&qw{Mon Tues Wednes Thurs Fri Satur Sun}[$x-1]."day"||"Invalid"
\$\endgroup\$
1
\$\begingroup\$

Lua 134 119 115 100 98

q={"mon","tues","wednes","thurs","fri","satur","sun"}print(n<8 and n>0 and q[n].."day"or"invalid")

Basically the same thought MartinButtner had, except about 4.5 4.1 1.7 1.4 times longer. Does assume n is stored as a variable elsewhere.

\$\endgroup\$
  • \$\begingroup\$ In fairness, you don't need any of that I/O here. \$\endgroup\$ – Martin Ender Aug 15 '14 at 15:27
  • \$\begingroup\$ @MartinBüttner: I think it's longer if I use a function \$\endgroup\$ – Kyle Kanos Aug 15 '14 at 15:27
  • \$\begingroup\$ Just expect n to be stored in a variable, as in the OP's snippet. \$\endgroup\$ – Martin Ender Aug 15 '14 at 15:30
  • \$\begingroup\$ yeah, I wasn't expecting any I/O on your side. \$\endgroup\$ – CrazyMod Aug 15 '14 at 15:31
1
\$\begingroup\$

Python (84)

lambda a:'imtwtfssnouehrauvneduitnadsnrdudladesaraiyasdydyd yda a    ay y    y'[a if 0<a<8 else 0::8]

I suppose it's an interesting sollution. It takes an idea from another answere I read somewhere (can't find it, I do know it was on this site, so if anyone knows feel free to tell me.) The string was generated with the following J program:

,|:>'invalid';'monday';'tuesday';'wednesday';'thursday';'friday';'saturday';'sunday'

Taking some subtle hints from this answer:

lambda a:' mtwtfssouehrauneduitn snr u   es r   s'[a::7]+'day'if 0<a<8 else'invalid'
\$\endgroup\$
1
\$\begingroup\$

Bash 74 48 + error message

A different approach since all other answers focus on storing the strings in some form.

read x;((0<x&&x<8))&&date -d2007010$x +%A||echo out of range
\$\endgroup\$
  • \$\begingroup\$ what is the byte count? \$\endgroup\$ – proud haskeller Aug 15 '14 at 18:46
  • \$\begingroup\$ @proudhaskeller Irrelevant as this has not been tagged as code-golf \$\endgroup\$ – user80551 Aug 15 '14 at 18:48
  • \$\begingroup\$ you're right, just all other solutions have a byte count. weird. \$\endgroup\$ – proud haskeller Aug 15 '14 at 18:49
  • \$\begingroup\$ That is more a POSIX sh answer. In bash you can use arithmetic evaluation. read x;((0<x&&x<8))&&date -d2007010$x +%A||echo out of range is shorter. \$\endgroup\$ – manatwork Aug 16 '14 at 16:25
  • \$\begingroup\$ The question only stated that the program should not crash in case the number is not between 1 and 7, so you can just remove the ||echo out of range. Considering that the accepted solution doesn't follow the rules (print to stdout)... But if you want to follow the OP's example, you can use invalid instead of out of range. \$\endgroup\$ – nyuszika7h Aug 18 '14 at 22:11
1
\$\begingroup\$

Perl, 54

From STDIN to STDOUT, no date functions, no crash.

print((a,Mon,Tues,Wednes,Thurs,Fri,Satur,Sun)[<>].day)
\$\endgroup\$
1
\$\begingroup\$

PHP (56 bytes)

$d=1;echo$d>0&&$d<8?date('D',255600+$d*86400):'Invalid';
\$\endgroup\$
1
\$\begingroup\$

Clojure - 99 chars

Plain and simple, despite my best (newbie) attempts:

(defn f[x](get{1"monday"2"tuesday"3"wednesday"4"thursday"5"friday"6"saturday"7"sunday"}x"invalid"))
\$\endgroup\$
1
\$\begingroup\$

JS: 58

Assuming n is already stored as a variable.

"0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun".split(0)[n%8]+"day"

As an ES6 function (same assumptions): 67

let d=n=>"0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun".split(0)[n%8]+"day"

This will just print "day" for 0 and loops around for n > 7

\$\endgroup\$
  • \$\begingroup\$ "Tueday"? Also, your description is inaccurate, it returns day for 8 and starts again from Monday at 9. \$\endgroup\$ – nyuszika7h Aug 17 '14 at 17:02
  • \$\begingroup\$ @nyuszika7h Thanks for the catch. \$\endgroup\$ – Isiah Meadows Aug 17 '14 at 20:20
1
\$\begingroup\$

Rebmu: 21 characters

pcSYSTEM/locale/daysA

To run:

>> rebmu/args {pcSYSTEM/locale/daysA} 1 
== "Monday"

Invalid numbers will return "none".

>> rebmu/args {pcSYSTEM/locale/daysA} 8 
== none

>> rebmu/args {pcSYSTEM/locale/daysA} 0
== none

For those unfamiliar with Rebmu, it uses case transitions to remove the need for spacing--within the limits of what's legally parseable. Rather than using a InitialCapsToBreak it uses CASEtransitionsTObreak, because that allows a different meaning to be ascribed to an initial run of capitals from if the initial initial run is lowercase.

So it is equivalent to the Rebol program pick system/locale/days a. (Rebmu by convention names its script parameter as "a").

Saves one character over system/locale/days/(a) :-)

\$\endgroup\$
1
\$\begingroup\$

Haskell - 62

Wraps around; 0 is Sunday, 8 is Monday, and so on.

words"Mon Tues Wednes Thurs Fri Satur Sun"!!(mod(n-1)7)++"day"

If printing to stdout is required (68 bytes, output is in double quotes):

print$words"Mon Tues Wednes Thurs Fri Satur Sun"!!(mod(n-1)7)++"day"
\$\endgroup\$
1
\$\begingroup\$

LiveScript - 49

Returns undefinedday if the input is invalid. ;)

<[Mon Tues Wednes Thurs Fri Satur Sun]>[n-1]+\day

If printing to stdout is required (60 bytes):

console.log<[Mon Tues Wednes Thurs Fri Satur Sun]>[n-1]+\day
\$\endgroup\$
1
\$\begingroup\$

Befunge-93 (206 208)

This one was fun to write. I'm sure it can be done in a better way, but… it works! =) Can be tried out here.

Would've been even shorter if the # would jump over entire strings rather than just the individual cell.

&1-    v
vv"Mon"># :# !_
> 1-    v
vv"Tues"># :# !_
> 1-      v
vv"Wednes"># :# !_
> 1-     v
vv"Thurs"># :# !_
> 1-   v
vv"Fri"># :# !_
> 1-     v
vv"Satur"># :# !_
> 1-   v
vv"Sun"># :# !_
>>:#,_"yad",,,@

The basic idea behind it: Get the number and keep decrementing it. Everytime we decrement it, the cursor moves to the right, wraps around and is sent one level lower. Once we hit zero, move to the left instead and push the (first part of the) day name. From then on, the cursor will move straight to the bottom where the string is printed and "day" is appended.

You can see how it works by using the "Step" feature in the link to the online interpreter.

Edit: I managed to shave two bytes off by doing >:#,_ instead of >,,,,,,, which is pretter as well.

\$\endgroup\$
1
\$\begingroup\$

MATLAB : 33

datestr(3:9,'dddd');ans(1:7==n,:)

MATLAB : 71

{'mon';'tues';'wednes';'thurs';'fri';'satur';'sun'};[ans{1:7==2} 'day']

Haskell : 75

g n=((++"day").last.take(abs n).words)"mon tues wednes thurs fri satur sun"

Haskell : 97

f n=if elem n[1..7]then["mon","tues","wednes","thurs","fri","satur","sun"]!!n++"day"else"invalid"

Python 3.4.1 : 81

'invalid mon tues wednes thurs fri satur sun'.split(' ')[n*(n in range(8))]+'day'
\$\endgroup\$
  • \$\begingroup\$ You probably should post these as separate answers. \$\endgroup\$ – nyuszika7h Aug 20 '14 at 10:10
  • \$\begingroup\$ In Python: (0<n<8) is shorter then (n in range(8)). split() also split string \$\endgroup\$ – AMK Aug 28 '14 at 14:54
1
\$\begingroup\$

Java 8 - 69 64 chars

Here's an expression in Java 8, including the import. Now improved (thanks to Tomáš Dvořák):

import java.time.*;
return DayOfWeek.of((i>0&i<8)?i:1).name();

Simply prints MONDAY for bogus values of i

\$\endgroup\$
  • \$\begingroup\$ Tip: .name() is shorter than .toString() and does the same thing. You can save 4 characters. Also you can use only one & instead of two and save another char. \$\endgroup\$ – Tomáš Dvořák Aug 29 '14 at 5:56
1
\$\begingroup\$

Python - 87

I'm not seeing enough love for dict's .get() This one expects a to be the number

dict(enumerate("mon,tues,wednes,thurs,fri,satur,sun".split(","),1)).get(a,"bad ")+"day"
\$\endgroup\$
  • \$\begingroup\$ You can save some characters by removing all occurrences of day in your list and add +"day" at the end of your code. \$\endgroup\$ – ProgramFOX Aug 31 '14 at 15:42
  • \$\begingroup\$ You can also save some characters by putting all days in one string and then split them instead of putting them all separately in the list: "mon,tues,...".split(",") \$\endgroup\$ – ProgramFOX Aug 31 '14 at 17:08
  • \$\begingroup\$ That works nicely, cheers :-) \$\endgroup\$ – deepy Aug 31 '14 at 17:38
0
\$\begingroup\$

Python, 95 bytes

"%day"%["mon","tues","wednes","thurs","fri","satur","sun"][n-1] if 0<n<8 else "invalid"
\$\endgroup\$
  • 2
    \$\begingroup\$ monsday? Did I read that right? \$\endgroup\$ – trichoplax Aug 15 '14 at 15:45
  • \$\begingroup\$ Not sure where you got 95 bytes from, by my count it's 88. I managed to save 11 by fixing the "monsday" bug, using string concatenation instead of % formatting, creating the list from a string using split() and removing unnecessary whitespace. \$\endgroup\$ – undergroundmonorail Aug 15 '14 at 16:42
  • 2
    \$\begingroup\$ "mon tues wednes thurs fri satur sun".split()[n-1]+"day"if 0<n<8else"invalid" \$\endgroup\$ – undergroundmonorail Aug 15 '14 at 16:43
  • \$\begingroup\$ @undergroundmonorail you can save another 6 bytes by using single quotes instead of double quotes \$\endgroup\$ – trichoplax Aug 15 '14 at 17:21
  • 2
    \$\begingroup\$ @githubphagocyte I can't tell if you're joking or seriously mistaken regarding how many bytes quote characters take up. \$\endgroup\$ – undergroundmonorail Aug 15 '14 at 17:24
0
\$\begingroup\$

Python 2, 84 83 64

Assuming n is already stored as a variable.

import calendar as c;print c.day_name[n-1]if 0<n<8 else'Invalid' 
\$\endgroup\$
0
\$\begingroup\$

Cobra - 43

print if(0<n<8,(n%7)to DayOfWeek,'Invalid')
\$\endgroup\$

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.