Input a number and return day of week

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"))))))));

• output full words (STDOUT)
• not crash if the input is less than 1 or greater than 7
• 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. – trichoplax Aug 15 '14 at 15:25
• 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). – Peter Taylor Aug 15 '14 at 15:31
• 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. – trichoplax Aug 15 '14 at 15:32
• Note that questions are language agnostic by default - you don't need to specify that it's not restricted to one programming language. – trichoplax Aug 15 '14 at 15:35
• 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. – nyuszika7h Aug 17 '14 at 15:07

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.

• Gah, I was just about to put a Lua version of this same thing (except it was going to be about 100 characters longer)... – Kyle Kanos Aug 15 '14 at 15:22
• 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! – CrazyMod Aug 15 '14 at 15:25
• Can you do n>0&n<8 (removing the second &) in Ruby? I know that works in Java. – bmarks Aug 15 '14 at 15:51
• @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). – Martin Ender Aug 15 '14 at 15:54
• 21 in Rebmu ... :-) – HostileFork says dont trust SE Aug 18 '14 at 0:33

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.).

• 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. – Cruncher Aug 15 '14 at 18:52
• 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. – yasen Aug 15 '14 at 19:26 • If you post this as an answer for date rather than Bash, it would be a mere 14-08-1$1 – 9 bytes! – Ingo Bürk Aug 15 '14 at 22:45
• It's 46 bytes, don't count the trailing newline; – nyuszika7h Aug 17 '14 at 10:50
• Well, more than 2 times shorter version :): codegolf.stackexchange.com/a/36424/11887 . – avall Aug 19 '14 at 13:18

Marbelous192191185 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

Javascript, 95 88 bytes

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.

• that's a neat method! – CrazyMod Aug 15 '14 at 15:28
• 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") – edc65 Aug 15 '14 at 21:41
• Ah, that's clever! I'll update my post now. – Sean Latham Aug 17 '14 at 22:01

C# - 26 Bytes

Expects the day to be stored inside n.
Does not crash, as expected.

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

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

• Can you remove the second & in the conditional? I don't think short circuit evaluation here is necessary. – bmarks Aug 15 '14 at 17:21
• @bmarks You're correct, thanks – William Barbosa Aug 15 '14 at 17:23
• 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) – Stephan Schinkel Aug 21 '14 at 11:10
• @StephanSchinkel Yeah, I guess you're right – William Barbosa Aug 21 '14 at 11:35

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";
• 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) – VisualMelon Aug 15 '14 at 16:01

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   ))

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));

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"

Lua 134119115100 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.

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

Python (84)

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'

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 • what is the byte count? – proud haskeller Aug 15 '14 at 18:46 • @proudhaskeller Irrelevant as this has not been tagged as code-golf – user80551 Aug 15 '14 at 18:48 • you're right, just all other solutions have a byte count. weird. – proud haskeller Aug 15 '14 at 18:49 • 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. – manatwork Aug 16 '14 at 16:25
• 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. – nyuszika7h Aug 18 '14 at 22:11

Perl, 54

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

print((a,Mon,Tues,Wednes,Thurs,Fri,Satur,Sun)[<>].day)

PHP (56 bytes)

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

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"))

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

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

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) :-)

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"

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

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"># :# !_

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.

MATLAB : 33

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

MATLAB : 71

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

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

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'
• You probably should post these as separate answers. – nyuszika7h Aug 20 '14 at 10:10
• In Python: (0<n<8) is shorter then (n in range(8)). split() also split string – AMK Aug 28 '14 at 14:54

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

• 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. – Tomáš Dvořák Aug 29 '14 at 5:56

Python - 87

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

• You can save some characters by removing all occurrences of day in your list and add +"day" at the end of your code. – ProgramFOX Aug 31 '14 at 15:42
• 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(",") – ProgramFOX Aug 31 '14 at 17:08
• That works nicely, cheers :-) – deepy Aug 31 '14 at 17:38

Python, 95 bytes

"%day"%["mon","tues","wednes","thurs","fri","satur","sun"][n-1] if 0<n<8 else "invalid"
• monsday? Did I read that right? – trichoplax Aug 15 '14 at 15:45
• 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. – undergroundmonorail Aug 15 '14 at 16:42
• "mon tues wednes thurs fri satur sun".split()[n-1]+"day"if 0<n<8else"invalid" – undergroundmonorail Aug 15 '14 at 16:43
• @undergroundmonorail you can save another 6 bytes by using single quotes instead of double quotes – trichoplax Aug 15 '14 at 17:21
• @githubphagocyte I can't tell if you're joking or seriously mistaken regarding how many bytes quote characters take up. – undergroundmonorail Aug 15 '14 at 17:24

Python 2, 8483 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'

Cobra - 43

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