연간 과제입니다


22

숫자가 1≤n≤365 인 경우 해당 연도의 n 번째 날을 "Day-numberth Month"형식으로 출력하십시오. 예를 들어, 1을 지정하면 "of"없이 "1 월 1 일"을 출력해야합니다.

Gregorian 달력이 사용되며 프로그램이 윤년을 설명해서는 안되므로 프로그램은 어떤 경우에도 "2 월 29 일"을 출력하지 않아야합니다. 앞에서 언급 한 "일수 월"형식을 따르는 한 모든 방법을 사용할 수 있습니다. 또한 프로그램은 서수를 올바르게 출력해야합니다. 즉, 항상 1, 2, 3을 1, 2 또는 3으로 입력해야합니다. 선행 공백 또는 다른 들여 쓰기가 허용됩니다.

이것은 코드 골프이므로 문자별로 가장 짧은 솔루션이 이깁니다.

테스트 사례 :

1 gives 1st January
2 gives 2nd January
3 gives 3rd January
365 gives 31st December
60 gives 1st March
11 gives 11th January

4
또한 365보다 큰 숫자로 오류 메시지를 표시해야합니까? 프로그램은 입력이 유효하지 않다고 가정 할 수 있으며 처리 할 필요가 없습니까?
— Rɪᴋᴇʀ

5
모든 사람이 영어를 모국어로 사용하는 것은 아니기 때문에 11, 12, 13 일은 "th", "1"로 끝나는 숫자는 "st", "2"는 "nd", "3"을 추가 할 수 있습니다. "rd"를, 다른 모든 "th"를 얻습니다.
— Adám

9
우와, 대답을 너무 빨리 받아들이지 마 특히 오답이 아닙니다 !
— Adám

6
당신은 적어도 추가해야합니다 11(11 일 년 1 월) 및 21(21 일 테스트 케이스에 월).
— Arnauld

1
테스트 사례를 편집하는 동안 테스트 사례 형식이 정확히 무엇인지 지정할 수 있습니다. 몇 명의 응답자들은 이것이 123=필요한 출력의 일부 라고 생각했습니다 . 또는 단순히 테스트 케이스를 편집하여 다음과 같이 읽으십시오. 365gives31st December
— Adám

답변:


9

PHP ,38 40 30 28 바이트

<?=date("jS F",86399*$argn);

온라인으로 사용해보십시오!

php -nF입력으로 실행 은에서 시작되었습니다 STDIN. 예 (위의 스크립트 위 y.php) :

$ echo 1|php -nF y.php
1st January
$ echo 2| php -nF y.php
2nd January
$ echo 3| php -nF y.php
3rd January
$ echo 11|php -nF y.php
11th January
$ echo 21|php -nF y.php
21st January
$ echo 60|php -nF y.php
1st March
$ echo 365|php -nF y.php
31st December

설명

day number * number of seconds per day(86400) 을 곱하여 1970 년에 원하는 날 (약간 윤년이 아님)에 대한 에포크 타임 스탬프를 구성합니다 . 그러나 이로 인해 하루가 더 높아 지므로 대신 number of seconds in a day - 1입력 숫자 범위 (1≤n≤365)에 대해 올바른 각 날의 타임 스탬프가 발생 하는 (86399)를 곱 하십시오. 그런 다음 PHP의 내장 날짜 형식을 사용하여 출력하십시오.


왜 -n필요한가?
— 벤

@Ven 모든 경우에 해당되는 것은 아니지만 로컬 php.ini에서 일관성없는 동작을 일으킬 수있는 설정을 비활성화합니다.
— 640KB

6

젤리 ,  79 78  77 바이트

-1 버그를 :) 수정하는 (인덱스를 찾을 수-전치을 미리 안, 역 게시해야한다, 그러나 우리가 할 수있는 꼬리가 아닌 머리)
-1 반사를 사용 ( ⁽©ṅB+30_2¦2-> ⁽0ṗb4+28m0)

⁽0ṗb4+28m0SRṁRƲœiµṪȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤$K

결과를 인쇄하는 전체 프로그램

온라인으로 사용해보십시오!

방법?

나중에 이것을 업데이트합니다 ...

⁽©ṅB+30_2¦2SRṁRƲZœiµḢȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“...»Ḳ¤$K - Main Link: integer, n
⁽©ṅB+30_2¦2SRṁRƲZœi - f(n) to get list of integers, [day, month]
⁽©ṅ                 - compressed literal 2741
   B                - to a list of binary digits -> [ 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1]
    +30             - add thirty                    [31,30,31,30,31,30,31,31,30,31,30,31]
         ¦          - sparse application...
        2           - ...to indices: [2]
       _  2         - ...action: subtract two       [31,28,31,30,31,30,31,31,30,31,30,31]
               Ʋ    - last four links as a monad - i.e. f(x):
           S        -   sum x                       365
            R       -   range                       [1..365]
              R     -   range x (vectorises)        [[1..31],[1..28],...]
             ṁ      -   mould like                  [[1..31],[32..59],...]
                Z   - transpose                     [[1,32,...],[2,33,...],...]
                 œi - 1st multi-dimensional index of n  -> [day, month]

µḢȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“...»Ḳ¤$K - given [day, month] format and print
µ                                  - start a new monadic chain - i.e. f(x=[day, month])
 Ḣ                                 - head -- get the day leaving x as [month])
  Ȯ                                - print it (with no newline) and yield it
   %30                             - modulo by thirty
      %20                          - modulo by twenty
         «4                        - minimum of that and four
                     ¤             - nilad followed by link(s) as a nilad:
            “nḄƲf⁷»                -   dictionary words "standard"+" the" = "standard the"
                   s3              -   split into threes = ["sta","nda","rd ","the"]
           ị                       - index into
                      Ṗ            - remove rightmost character
                               ¤   - nilad followed by link(s) as a nilad:
                         “...»     -   dictionary words "January"+" February"+...
                              Ḳ    -   split at spaces = ["January","February",...]
                        ị          - index into (vectorises across [month])
                       ,           - pair                  e.g. ["th", ["February"]]
                                K  - join with spaces           ["th ", "February"]
                                   - print (implicitly smashes)   th February

4
"표준"트릭은 놀랍습니다.
— 벤

@Ven에 동의합니다 . 또한 압축 된 문자열 을 크기 2 ( )의 부분으로 나누는 것에 비해 05AB1E 답변 에 바이트를 저장 했으므로 감사합니다. :)"thstndrd".•oθ2(w•2ô
— Kevin Cruijssen

1
이것은 내가 본 것 중 가장 긴 Jelly 프로그램 중 하나 여야합니다.
— JAD

6

C 번호 (카메라 C 번호 인터랙티브 컴파일러) , 115 (113) 109 98 바이트

g=>$"{f=(g=p.AddDays(g-1)).Day}{"tsnr"[f=f%30%20<4?f%10:0]}{"htdd"[f]} {g:MMMM}";DateTime p;int f;

9 바이트를 절약 한 @someone에게 감사합니다

온라인으로 사용해보십시오!


1
@KevinCruijssen 나는 모듈로가 고장났습니다. 지금 고쳐야합니다.
— 무지의 구현

.code.tio(2,22): error CS0165: Use of unassigned local variable 'p'구조체가 작동하지 않는 것 같습니다.
— JAD

var g=new DateTime().AddDays(n-1)그래도 작동
— JAD

@JAD 실수, 고정
— 무지의 구현


5

Python 3.8 (시험판) , 112 바이트

lambda x:str(d:=(t:=gmtime(x*86399)).tm_mday)+'tsnrhtdd'[d%5*(d%30%20<4)::4]+strftime(' %B',t)
from time import*

온라인으로 사용해보십시오!

이상하게도, d:=(t:=gmtime(~-x*86400)인터프리터 ()는 할당 표현식 주위 에 문자 가 있는지 확인 하고 표현식 자체가 괄호로 묶여 있지 않은지 확인하기 때문에 괄호로 묶을 필요는 없습니다 .

gwaugh 덕분에 -2 .
덕분에 -5xnor .


5

펄 6 , 166161 바이트

{~(.day~(<th st nd rd>[.day%30%20]||'th'),<January February March April May June July August September October November December>[.month-1])}o*+Date.new(1,1,1)-1

온라인으로 사용해보십시오!

모든 월 이름을 하드 코드하여 대부분의 공간을 차지합니다. Man, Perl 6에는 실제로 적절한 날짜 포맷터가 필요합니다.


4

해킹, 115 59 39 바이트

$x==>date("jS F",mktime(0,0,0,1,$x));

골프를 칠 때 @gwaugh가 내 솔루션과 동일한 솔루션을 얻었으므로 대신 Hack에 게시하고 있습니다. :)


와우, 좋은 생각은 비슷하게 생각합니다. :) +1 선생님 께!
— 640KB

@gwaugh haha, 나는 최상위 프로그램을 가질 수 있다는 것을 몰랐다. 나는 그것을 최상위 수준으로 만들기 위해 편집하고 더 나은 점수를 얻는 방법을 찾을 것이다 ;-)
— Ven

1
@gwaugh 대신 내 핵을 만들었습니다.
— 벤

1
윤년이 아닌 연도 매개 변수를 mktime()호출 에 지정하려는 경우 윤년에 실행하면 잘못된 출력이 반환됩니다. (내 대답에해야했다).
— 640KB

4

자바 스크립트 (ES6),  117  113 바이트

@tsh 덕분에 4 바이트 절약

d=>(n=(d=new Date(1,0,d)).getDate())+([,'st','nd','rd'][n%30%20]||'th')+' '+d.toLocaleString('en',{month:'long'})

온라인으로 사용해보십시오!

댓글

d =>                     // d = input day
  ( n =                  //
    ( d =                // convert d to
      new Date(1, 0, d)  //   a Date object for the non leap year 1901
    ).getDate()          // save the corresponding day of month into n
  ) + (                  //
    [, 'st', 'nd', 'rd'] // ordinal suffixes
    [n % 30 % 20]        // map { 1, 2, 3, 21, 22, 23, 31 } to { 'st', 'nd', 'rd' }
    || 'th'              // or use 'th' for everything else
  ) + ' ' +              // append a space
  d.toLocaleString(      // convert d to ...
    'en',                // ... the English ...
    { month: 'long' }    // ... month name
  )                      //

날짜 내장없이 188 바이트

f=(d,m=0)=>d>(k=31-(1115212>>m*2&3))?f(d-k,m+1):d+([,'st','nd','rd'][d%30%20]||'th')+' '+`JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember`.match(/.[a-z]*/g)[m]

온라인으로 사용해보십시오!


매월 11 일, 12 일, 13 일에 실패
— 데이터 만료

1
@ExpiredData 이것을보고 해 주셔서 감사합니다. 지금 수정했습니다.
— Arnauld

내 의견을 무시하고 ID10T 오류가 발생했습니다.
— asgallant

nodejs가 언어 태그를 처리하는 방법을 잘 모르겠지만 사용하는 것처럼 0작동 하는 것 같습니다 "en". 로 변경 toLocaleString하면 4 바이트가 절약됩니다. 110 바이트
— tsh

@tsh toLocaleString인식 할 수없는 문자열이나 숫자 값이 전달 될 때 시스템 기본 설정을 사용하고있는 것 같습니다 . 따라서 무엇이든 될 수 있습니다. 어쨌든 영어 로케일 만 설치 되므로이 매개 변수는 기본적으로 TIO 인스턴스에서 유효하지 않습니다 .
— Arnauld

4

스몰 토크, 126 바이트

d:=Date year:1day:n.k:=m:=d dayOfMonth.10<k&(k<14)and:[k:=0].o:={#st.#nd.#rd}at:k\\10ifAbsent:#th.m asString,o,' ',d monthName

1
스몰 토크를 모르지만 이것이 맞 11th,12th,13th습니까? 올바르게 읽으면 하루를 10으로 정수 나눕니다.하지만 11st,12nd,13rd코드의 다른 것이 이것을 모르는 동안이 문제를 해결하지 않으면 결과가 될 것입니다.
— 케빈 크루이 센

@KevinCruijssen 당신이 맞아요. 이것에 관심을 가져 주셔서 감사합니다. 이 문제를 해결하려면 더 많은 바이트를 사용해야합니다.
— Leandro Caniglia

1
@KevinCruijssen, 완료 다시 감사합니다.
— Leandro Caniglia

3

C 번호 (카메라 C 번호 인터랙티브 컴파일러) , 141 (139) 133 124 122 바이트

a=>{var d=s.AddDays(a-1);int x=d.Day,m=x%30%20;return x+"thstndrd".Substring(m<4?m*2:0,2)+d.ToString(" MMMM");};DateTime s

11,12,13 번째 4 바이트를 절약하는 빠른 방법을 제공하는 Arnauld 덕분에

온라인으로 사용해보십시오!


C # 8을 사용하면 다음과 같이 줄일 수 있습니다 a=>{var d=s.AddDays(a-1);int x=d.Day,m=x%30%20;return x+"thstndrd"[(m<4?m*2:0)..2]+$" {d:MMMM}";};DateTime s . 대화 형 컴파일러는 현재 언어 수준을 "미리보기"로 변경하는 것을 지원하지 않는 것 같습니다.
— Arcanox


1 DataTime s
— 무지의 구체화


3

MySQL, 47 45 42 바이트

SELECT DATE_FORMAT(MAKEDATE(1,n),"%D %M")

1901은 윤년이 아닌 연도로 대체 할 수 있습니다.

편집 : @Embodyment of Ignorance 덕분에 공백을 제거하여 2 바이트를 절약하고 연도를 1로 변경하여 다른 3 바이트를 절약했습니다 .


1901, n문자열 사이의 공백을 제거 할 수 있습니까 ?
— 무지의 구현

@EmbodimentofIgnorance 네, 감사합니다!
— NicolasB

또한 1901을 1과 같은 연도로 바꾸지 않겠습니까? 1 윤년하지이며, 3 바이트 짧다
— 무지의 실시 예

@EmbodimentofIgnorance done and done :-)
— NicolasB

3

05AB1E , 81 79 78 76 75 74 73 71 70 69 바이트

•ΘÏF•ºS₂+.¥-D0›©ÏθDT‰ć≠*4šß„—ÊØ3ôsè¨ð”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”#®OèJ

@Grimy 덕분에 -9 바이트 .
@JonathanAllan의 standard the트릭 덕분에 -1 바이트 덕분에 Jelly 답변에th,st,nd,rd 사용되었습니다 .

온라인으로 시도 하거나 가능한 모든 테스트 사례를 확인하십시오 .

설명:

•ΘÏF•        # Push compressed integer 5254545
     º       # Mirror it vertically: 52545455454525
      S      # Converted to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5]
       ₂+    # And 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
             # (the additional trailing 28,31 won't cause any issues)
.¥           # Undelta this list (with automatic leading 0):
             #  [0,31,59,90,120,151,181,212,243,273,304,334,365,393,424]
  -          # Subtract each from the (implicit) input-integer
   D0›       # Duplicate the list, and check for each if it's positive (> 0)
      ©      # Store the resulting list in the register (without popping)
       Ï     # Only leave the values at those truthy indices
        θ    # And get the last value from the list, which is our day
D            # Duplicate this day
 T‰          # Take the divmod-10 of this day: [day//10, day%10]
   ć         # Extract the head; pop and push the remainder-list and head: [day%10], day//10
    ≠        # Check whether the day//10 is NOT 1 (0 if day//10 == 1; 1 otherwise)
     *       # Multiply that by the [day%10] value
      4š     # Prepend a 4 to this list
        ß    # Pop and push the minimum of the two (so the result is one of [0,1,2,3,4],
             # where the values are mapped like this: 1..3→1..3; 4..9→4; 10..19→0; 20..23→0..3; 24..29→4; 30,31→0,1)
 …thŠØ       # Push dictionary string "th standards"
      3ô     # Split it into parts of size 3: ["th ","sta","nda","rds"]
        sè   # Swap and index the integer into this list (4 wraps around to index 0)
          ¨  # And remove the trailing character from this string
ð            # Push a space " "
”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”
             # Push dictionary string "December January February March April May June July August September October November"
 #           # Split on spaces
  ®          # Push the list of truthy/falsey values from the register again
   O         # Get the amount of truthy values by taking the sum
    è        # Use that to index into the string-list of months (12 wraps around to index 0)
J            # Join everything on the stack together to a single string
             # (and output the result implicitly)

이유를 이해하려면 이 05AB1E 팁을 참조하십시오 .

  • (섹션에서는 어떻게 사전을 사용하는 방법? ) ”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”입니다"December January February March April May June July August September October November"
  • (섹션에서는 어떻게 사전을 사용하는 방법? ) …thŠØ입니다"th standards"
  • ( 큰 정수를 압축하는 방법? ) 섹션 •ΘÏF•은5254545

1
압축에 5в28 +를 사용하여 -2 바이트 : TIO
— Grimmy

1
S를 사용하는 것이 좋습니다 -1 바이트 다시 : TIO
— Grimmy

1
@Grimy에 대한 -1 바이트를 주셔서 감사 •EË7Óæ•S₂+하지만 -3 골프는 불행히도 작동하지 않습니다. 인덱싱은 05AB1E에서 자동으로 래핑되므로 5st,6nd,7rd,25st,26nd,27rd,29st잘못된 것입니다. 추신 : 그것이 효과가 있다면 추가로 -1 일 <Ā수 있었을 것 ≠입니다. :)
— Kevin Cruijssen

1
다시 -1 ( "standard the"대신 "th standard"를 사용하면 필요 없음 Á).
— 그리미

1
-1 ( •C.ñÒā•에서 •ΘÏF•º, 추가 숫자는 중요하지 않음)
— Grimmy

2

세게 때리다, 82 80 bytes

@ASCII 전용으로 -2 바이트

a=(th st nd rd);set `printf "%(%e %B)T" $[$1*86399]`;echo $1${a[$1%30%20]-th} $2

TIO

bash + GNU 날짜, 77 바이트

a=(th st nd rd);set `date -d@$[$1*86399] +%e\ %B`;echo $1${a[$1%30%20]-th} $2


@ASCII-only, yes subtracting 100s for each day, 100*365 = 36500s which is less than one day (86400), works also with 86399 (subtract 1s by day)
— Nahuel Fouilleul

:/ still looks really long but haven't found a better way yet
— ASCII-only

2

Shell + coreutils, 112 90 bytes

date -d0-12-31\ $1day +%-dth\ %B|sed 's/1th/1st/;s/2th/2nd/;s/3th/3rd/;s/\(1.\).. /\1th /'

Try it online! Link includes test cases. Edit: Saved 22 bytes thanks to @NahuelFouilleul. Explanation:

date -d0-12-31\ $1day

Calculate the number of day(s) after the first day preceding a non-leap year. (Sadly you can't do relative date calculations from @-1.)

+%-dth\ %B|sed

Output the day of month (without leading zero), th, and the full month name.

's/1th/1st/;s/2th/2nd/;s/3th/3rd/;

Fix up 1st, 2nd, 3rd, 21st, 22nd, 23rd and 31st.

s/\(1.\).. /\1th /'

Restore 11th to 13th.


i saw this answer after mine, could save 18bytes using one sed command, also s in days can be removed, and 19 in 1969
— Nahuel Fouilleul

@NahuelFouilleul That last one uses a Bash-ism so should be posted as a separate answer, but thanks for the other tips!
— Neil

2

Jelly, 115 114 101 97 bytes

%30%20¹0<?4Ḥ+ؽị“thstndrd”ṭ
“5<Ḟ’b4+28ÄŻ_@µ>0T,>0$ƇZṪµ1ịị“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤,2ịÇƊṚK

Try it online!

Long by Jelly standards, but done from first principles.

Thanks to @JonathanAllan for saving 13 bytes through better understanding of string compression.


“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤ would save 13 (Compress.dictionary looks for a leading space and has special handling for it).
— Jonathan Allan

2

Google Sheets, 118 103 86 bytes

=day(A1+1)&mid("stndrdth",min(7,1+2*mod(mod(day(A1+1)-1,30),20)),2)&text(A1+1," mmmm")

I can't edit my comment so, here's a working version of the Google Sheets code.

Try it Online!


1

Red, 124 bytes

func[n][d: 1-1-1 + n - 1[rejoin[d/4 either 5 > t: d/4 % 30 % 20[pick[th st nd rd]t + 1]['th]]pick system/locale/months d/3]]

Try it online!

Adds n - 1 days to 1-1-1 (1-Jan-2001) to form a date, than uses Arnauld's method to index into month suffixes. Too bad Red is 1-indexed, this requires additional tweaking. The good thing is that Red knows the names of the months :)


1

APL(NARS), 235 chars, 470 bytes

{k←↑⍸0<w←+\v←(1-⍵),(12⍴28)+13561787⊤⍨12⍴4⋄k<2:¯1⋄d←1+v[k]-w[k]⋄(⍕d),({d∊11..13:'th'⋄1=10∣d:'st'⋄2=10∣d:'nd'⋄3=10∣d:'rd'⋄'th'}),' ',(k-1)⊃(m≠' ')⊂m←'January February March April May June July August September October November December'}

13561787 is the number that in base 4 can be summed to (12⍴28) for obtain the lenght of each month... test:

  f←{k←↑⍸0<w←+\v←(1-⍵),(12⍴28)+13561787⊤⍨12⍴4⋄k<2:¯1⋄d←1+v[k]-w[k]⋄(⍕d),({d∊11..13:'th'⋄1=10∣d:'st'⋄2=10∣d:'nd'⋄3=10∣d:'rd'⋄'th'}),' ',(k-1)⊃(m≠' ')⊂m←'January February March April May June July August September October November December'}     
  ⊃f¨1 2 3 365 60 11
1st January  
2nd January  
3rd January  
31st December
1st March    
11th January 

0

C (gcc), 174 155 bytes

i;char a[99],*b="thstndrd";f(long x){x--;x*=86400;strftime(a,98,"%d   %B\0",gmtime(&x));i=*a==49?0:a[1]-48;a[2]=b[i=i>3?0:i*2];a[3]=b[++i];x=*a==48?a+1:a;}

Try it online!


-2

Python 3, 95 Bytes

Datetimed it :P

from datetime import *;f=lambda s:(datetime(2019,1,1)+timedelta(days=s-1)).strftime("%d of %B")

Try it online!


2
This doesn't produce the ordinal suffixes, and has leading zeroes in the day number. The of is also unnecessary
— Jo King
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.