Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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
share|improve this question
6  
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. –  githubphagocyte Aug 15 at 15:25
9  
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 at 15:31
2  
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. –  githubphagocyte Aug 15 at 15:32
2  
Note that questions are language agnostic by default - you don't need to specify that it's not restricted to one programming language. –  githubphagocyte Aug 15 at 15:35
2  
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 at 15:07

45 Answers 45

up vote 8 down vote accepted

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.

share|improve this answer
    
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 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 at 15:25
    
Can you do n>0&n<8 (removing the second &) in Ruby? I know that works in Java. –  bmarks Aug 15 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 Büttner Aug 15 at 15:54
1  
21 in Rebmu ... :-) –  Dr. Rebmu Aug 18 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.).

share|improve this answer
    
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 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 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 at 22:45
    
It's 46 bytes, don't count the trailing newline; –  nyuszika7h Aug 17 at 10:50
    
Well, more than 2 times shorter version :): codegolf.stackexchange.com/a/36424/11887 . –  avall Aug 19 at 13:18

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
share|improve this answer

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.

share|improve this answer
    
that's a neat method! –  CrazyMod Aug 15 at 15:28
1  
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 at 21:41
    
Ah, that's clever! I'll update my post now. –  ipi Aug 17 at 22:01

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

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

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

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

;; call main
&main
share|improve this answer

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.

share|improve this answer

Javascript 93 :(

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

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.

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

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

share|improve this answer
    
Why September of 2014 and not January 1st year 1 AD? –  Dr. Rebmu Aug 17 at 18:52
    
The answer is: I failed to think of it. But I will incorporate your suggestion. –  David Carraher Aug 19 at 11:16

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));
share|improve this answer

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"
share|improve this answer

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.

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

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'
share|improve this answer

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

Perl, 54

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

print((a,Mon,Tues,Wednes,Thurs,Fri,Satur,Sun)[<>].day)
share|improve this answer

PHP (56 bytes)

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

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"))
share|improve this answer

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

share|improve this answer
    
"Tueday"? Also, your description is inaccurate, it returns day for 8 and starts again from Monday at 9. –  nyuszika7h Aug 17 at 17:02
    
@nyuszika7h Thanks for the catch. –  impinball Aug 17 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) :-)

share|improve this answer

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"
share|improve this answer

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
share|improve this answer

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.

share|improve this answer

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

share|improve this answer
    
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 at 5:56
    
Thanks for the tips... great points –  Michael Easter Aug 29 at 11:35

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"
share|improve this answer
    
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 at 15:42
    
Ooh, nice one, thanks :-) –  deepy Aug 31 at 17:04
    
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 at 17:08
    
That works nicely, cheers :-) –  deepy Aug 31 at 17:38

Python, 95 bytes

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

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' 
share|improve this answer
    
From this comment, it does seem like input can be ignored. –  Kyle Kanos Aug 15 at 16:11
    
Thanks, edited. –  fsfd1100 Aug 16 at 0:43

Cobra - 43

print if(0<n<8,(n%7)to DayOfWeek,'Invalid')
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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